@@ -611,6 +611,117 @@ func TestIsCompleteTree(t *testing.T) {
611611 }
612612}
613613
614+ func TestIsPerfectTree (t * testing.T ) {
615+ // A perfect binary tree
616+ //
617+ // 1
618+ // / \
619+ // 2 3
620+ //
621+ root := binarytree .NewNode (1 )
622+ root .InsertLeft (2 )
623+ root .InsertRight (3 )
624+
625+ if ! root .IsPerfectTree () {
626+ t .Fatal ("tree should be perfect" )
627+ }
628+
629+ // A non-perfect binary tree
630+ //
631+ // 1
632+ // / \
633+ // 2 3
634+ // /
635+ // 4
636+ //
637+ root = binarytree .NewNode (1 )
638+ root .InsertRight (3 )
639+ two := root .InsertLeft (2 )
640+ two .InsertLeft (4 )
641+
642+ if root .IsPerfectTree () {
643+ t .Fatal ("tree should not be perfect" )
644+ }
645+
646+ // A non-perfect binary tree
647+ //
648+ // __1__
649+ // / \
650+ // 2 3
651+ // / \ /
652+ // 4 5 6
653+ //
654+ root = binarytree .NewNode (1 )
655+ two = root .InsertLeft (2 )
656+ two .InsertLeft (4 )
657+ two .InsertRight (5 )
658+ three := root .InsertRight (3 )
659+ three .InsertLeft (6 )
660+
661+ if root .IsPerfectTree () {
662+ t .Fatal ("tree should not be perfect" )
663+ }
664+
665+ // A perfect binary tree
666+ //
667+ // __1__
668+ // / \
669+ // 2 3
670+ // / \ / \
671+ // 4 5 6 7
672+ //
673+ root = binarytree .NewNode (1 )
674+ two = root .InsertLeft (2 )
675+ two .InsertLeft (4 )
676+ two .InsertRight (5 )
677+ three = root .InsertRight (3 )
678+ three .InsertLeft (6 )
679+ three .InsertRight (7 )
680+
681+ if ! root .IsPerfectTree () {
682+ t .Fatal ("tree should be perfect" )
683+ }
684+
685+ // A non-perfect binary tree
686+ //
687+ // 1
688+ // /
689+ // 2
690+ // /
691+ // 3
692+ //
693+ root = binarytree .NewNode (1 )
694+ two = root .InsertLeft (2 )
695+ two .InsertLeft (3 )
696+
697+ if root .IsPerfectTree () {
698+ t .Fatal ("tree should not be perfect" )
699+ }
700+
701+ // A non-perfect binary tree
702+ //
703+ // 1__
704+ // / \
705+ // 2 3
706+ // / \
707+ // 4 5
708+ root = binarytree .NewNode (1 )
709+ root .InsertLeft (2 )
710+ three = root .InsertRight (3 )
711+ three .InsertLeft (4 )
712+ three .InsertRight (5 )
713+
714+ if root .IsPerfectTree () {
715+ t .Fatal ("tree should not be perfect" )
716+ }
717+
718+ // A perfect binary tree with a single root node
719+ root = binarytree .NewNode (1 )
720+ if ! root .IsPerfectTree () {
721+ t .Fatal ("tree should be perfect" )
722+ }
723+ }
724+
614725func TestNodeAttributes (t * testing.T ) {
615726 root := binarytree .NewNode (1 )
616727
0 commit comments