lab8soln - private int isPerfectOfHeight(BTNode<E>...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
1. public int count() { return count (root); } private int count(BTNode<E> node) { if (node == null) return 0; else return 1 + count(node.left) + count(node.right); } 2. public int height() { return height(root); } private int height(BTNode<E> node) { if (node == null) return -1; else { int leftHeight = height(node.left); int rightHeight = height(node.right); if (leftHeight < rightHeight) return 1 + rightHeight; else return 1 + leftHeight; } } 3. // A tree is perfect if both subtrees are perfect and with the same height public boolean isPerfect() { return (isPerfectOfHeight(root) != -1); } // Returns the height+1 if the tree is perfect and -1 otherwise
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: private int isPerfectOfHeight(BTNode<E> node) { if (node == null) return 0; int leftHeight = isPerfectOfHeight(node.left); if (leftHeight != -1 && leftHeight == isPerfectOfHeight(node.right)) { return leftHeight + 1; } else { return -1; } } // A common solution, but slower than above (why?) public boolean isPerfect() { return isPerfect(root); } private boolean isPerfect(BTNode<E> node) { if (node == null) return true; else { int leftHeight = height(node.left); int rightHeight = height(node.right); return (leftHeight == rightHeight && isPerfect(node.left) && isPerfect(node.right)); } }...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online