- Print Ancestors of a given node in Binary Tree - very sweet problem. If the element is on the left subtree or the right subtree from this element, then this element is an ancestor. So, basically its like search on the left and right subtree. Formulate it recursively : http://www.geeksforgeeks.org/print-ancestors-of-a-given-node-in-binary-tree/
- LCA of two nodes in a BST : looks complicated. There are few frameworks for all BST problems, traversal or search. Search basically is also a form of traversal only. Just my way of thinking and categorizing.
Node *LCA(Node *root, Node *p, Node *q) {
if
(!root)
return
NULL;
if
(root == p || root == q)
return
root;
Node *L = LCA(root->left, p, q);
Node *R = LCA(root->right, p, q);
if
(L && R)
return
root;
// if p and q are on both sides
return
L ? L : R;
// either one of p,q is on one side OR p,q is not in L&R subtrees
}
- sd
- sd
Apart from coding and design interview questions, this page contains updates on my learnings with Java. It helps me organize my learning. Read about my future self here : https://siliconvalleystories.blogspot.com/
Sunday, 3 February 2013
BST problems where the underlying thing happenning is search - whatever be the name of the function
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment