/** * Determines the depth of the node with the specified key, * returning -1 if
ID: 3632789 • Letter: #
Question
/**
* Determines the depth of the node with the specified key,
* returning -1 if there is no such node.
*/
public int depth(int key) {
return -1;
}
this iterative method should take advantage of the fact that the tree is binary search tree, and should return -1 if the specified key is not found in the tree.
Explanation / Answer
function int getDepth (Node head, string val){if (head == NULL)return -1;if (val == head.Value)return head.Depth;return MAX(getDepth(head.Left), getDepth(head.Right);} function void setDepth (Node head){Stack s = new Stack();head.Depth = 0;s.push(head);while(s.count > 0){Node temp = s.pop();if (temp != NULL){if (temp.Left != NULL){temp.Left.Depth = temp.Depth + 1;s.push(temp.Left);}if (temp.Right != NULL){temp.Right.Depth = temp.Depth + 1;s.push(temp.Right);}}}} function int getDepth (Node head, string val){Stack s = new Stack();s.push(head);while(s.count > 0){Node temp = s.pop();if (temp != NULL){if (s.Value == val)return s.Depth;else{s.push(temp.Left);s.push(temp.Right);}}}return -1;}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.