Given a binary search tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia : "For two nodes u and v of a rooted tree T, the nearest common ancestor represents a node x, which satisfies that x is the ancestor of u and v and the depth of x is as large as possible." (A node can also be its own ancestor)
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the node 2
and 8
the nearest common ancestor are 6
. As another example, the last common ancestor of a node 2
sum 4
is 2
, because by definition the last common ancestor of a node can be the specified node itself.
Ideas:
- If the value of root is equal to the value of p, q, then return root
-
If the value of root is in the middle of the value of p, q, then the root is the common ancestor of p, q
-
If the value of root is greater than the value of p and q, find the common ancestor of p, q in the left subtree of root
-
If the value of root is greater than the values of p and q, find the common ancestor of p, q in the right subtree of root
1 class Solution { 2 public: 3 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 if(root->val == p->val || root->val == q->val) return root; 5 if((root->val > p->val && root->val < q->val)||(root->val < p->val && root->val > q->val)) return root; 6 if(root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q); 7 if(root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p,q); 8 } 9 };