Question:
In a binary integer value tree, find the lowest level common ancestor of the values.
http://www.glassdoor.com/Interview/ In-a-binary-integer-value-tree-find-the-lowest-level-common-ancestor-of-two-values-qtn_219955.htm
class treenode{// int val;// treenode left; // treenode right;// }//// lowest common ancestor question/ if it is a bst tree// given root, if two inputs are both smaller than root, the common ancestor must be on the root left.// if two inputs are both bigger than root, the common ancestor must be on the right// otherwise, the root is the common ancestor.public TreeNode Findlowestcommonancestor (treenode root, treenode a, treenode b) { // Input validations // root cannot be null. // a | | b&nbSp;cannot be null. // a and b must be node in the tree. if (a.val < Root.val && b.val < root.val) Return findlowestcommonancestor (root.left, a, b); else if ( A.val > root.val && b.val > root.val) return findlowestcommonancestor (root.right, a, b); else return root;} for bt// we can buttom-up// o (n) public treenode Findlowestcommonancestor (treenode root, treenode a, treenode b) { if (root == null) return null; if (root == a | | &NBSP;ROOT&NBSP;==&NBSP;B) return root; TreeNode findLeft = Findlowestcommonancestor (root.left, a, b); treenode findright = findlowestcommonancestor (root.right, a, b); if (findLeft != null && findright != null) return root; else if (findleft != null) return findLeft; else return findright ;} Or we can top down//// If it is just a normal bt// given a root//&Nbsp;define hit (root, a, b):int// as the number of nodes in Root.// if a and b are both in root, hit = 2// if only a in root or only b in root, hit = 1// Otherwise hit = 0//// o (n^2) : for each node, iterate the whole tree.public treenode findlowestcommonancestor (Treenode root, treenode &NBSP;A,&NBSP;TREENODE&NBSP;B) { int lefthit = hit (root, a, b); if (lefthit == 1) return root; else if (LEFTHIT&NBSP;==&NBSP;2) return findlowestcommonancestor ( ROOT.LEFT,&NBSP;A,&NBSP;B); else return Findlowestcommonancestor (root.right, a,&NBSP;B);} assume a != bprivate int hit (treenode node, treenode a, TREENODE&NBSP;B) { if (node == null | | a == null | | b == null) return 0; int r = 0; if (Node == a) { a = null; r ++; } if (node == b) { b = null; r ++; } return r + hit ( NODE.LEFT,&NBSP;A,&NBSP;B) + hit (node.right, a, b);}
[Twitter] Lowest level Common Ancestor