Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes
v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / ___2__ ___8__ / / 0 _4 7 9 / 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a
node can be a descendant of itself according to the LCA definition.
求最近的公共祖先,很显然,对于二叉搜索树来说,当两个节点的值都比root小的时候,lca应该在root左节点这一侧, 都比root值大的时候都在右节点这一侧,否则root
就是lca,代码见下所示:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 if(max(p->val, q->val) < root->val) 14 lowestCommonAncestor(root->left, p, q); 15 else if(min(p->val, q->val) > root->val) 16 lowestCommonAncestor(root->right,p ,q); 17 else 18 return root; 19 } 20 };
而对于非二叉搜索树来说,做法一般是先分别查找到到P以及Q的路线,然后对比路线,找出LCA,代码如下:
1 class Solution { 2 public: 3 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 if(root == NULL || p == NULL || q == NULL) 5 return NULL; 6 vector<TreeNode *>pathP; 7 vector<TreeNode *>pathQ; 8 pathP.push_back(root); 9 pathQ.push_back(root); 10 getPath(root, p, pathP); 11 getPath(root, q, pathQ); 12 TreeNode * lca = NULL; 13 for(int i = 0; i < pathP.size() && i < pathQ.size(); ++i){ 14 if(pathP[i] == pathQ[i]) //检查lca 15 lca = pathP[i]; 16 else break; 17 } 18 return lca; 19 } 20 21 bool getPath(TreeNode * root, TreeNode * target, vector<TreeNode * > & path) 22 { 23 if(root == target) 24 return true; 25 if(root->left){ 26 path.push_back(root->left); 27 if(getPath(root->left, target, path)) return true; 28 path.pop_back(); 29 } 30 if(root->right){ 31 path.push_back(root->right); 32 if(getPath(root->right, target, path)) return true; 33 path.pop_back(); 34 } 35 return false; 36 } 37 };
java版本的如下所示:
1 public class Solution { 2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 if(Math.max(p.val, q.val) < root.val){ 4 return lowestCommonAncestor(root.left, p, q); 5 }else if(Math.min(p.val, q.val) > root.val){ 6 return lowestCommonAncestor(root.right, p, q); 7 }else{ 8 return root; 9 } 10 } 11 }