Consider the following definition of IntTreeNode and IntTree, a binary search tr
ID: 3848396 • Letter: C
Question
Consider the following definition of IntTreeNode and IntTree, a binary search tree of integers which includes an add method, a "rotate your head left 90 degrees" print method like the one shown in class, and a launcher for a recursive depth method for IntTree. The depth method should print the maximum depth of the tree (depth being the maximum distance from the top of the tree, the root node itself having distance 1, its left and right children having distance 2, their children having distance 3, and so forth). Please select a working depth method for IntTree. An example main method is provided with the correct value in a comment. Explain why please!
private int depth(IntTreeNode node) { return 1 + Math.max(node.left, node.right); }
Explanation / Answer
The correct method is as follows: -
The things we need in the method is that, if the tree is null, it means root it empty so, depth will be zero. (So first option is wrong)
Else we need to calculate depth of the tree as follows: -
Traverse the tree and add 1 for each level of tree. The function needs to be recursive, so we need to calculate depth of left and right subtree each time. We need at each level to check which has max depth left tree or right tree.
So option c is right.