Java Reference
In-Depth Information
private int countLeaves(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 1;
return countLeaves(root.left) + countLeaves(root.right);
}
And the next returns the height of the tree:
public int height() {
return numLevels(root);
}
private int numLevels(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(numLevels(root.left), numLevels(root.right));
}
Math.max returns the larger of its two arguments.
You are advised to dry-run these functions on some sample trees to verify that they do return the correct values.
8.11 Binary Search Tree Deletion
Consider the problem of deleting a node from a binary search tree (BST) so that it remains a BST. There are three
cases to consider:
1.
The node is a leaf.
2.
(a) The node has no left subtree.
(b) The node has no right subtree.
3.
The node has non-empty left and right subtrees.
We illustrate these cases using the BST shown in Figure 8-9 .
H
L
F
R
A
J
T
N
C
D
P
B
Figure 8-9. A binary search tree
 
Search WWH ::




Custom Search