Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

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).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

 

更新于20180513

 

 

若pq都在某个节点的左边,就到左子树中查找,如果都在右边 就到右子树种查找。

要是pq不在同一边,那就表示已经找到第一个公共祖先。

 

 1 class Solution {
 2     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 3         if(!cover(root,p)||!cover(root,q)) return null;
 4         return LCAhelp(root,p,q);
 5     }
 6     private  TreeNode LCAhelp(TreeNode root,TreeNode p,TreeNode q ){
 7         if(root==null) return null;
 8         if(root==p||root==q) return root;
 9         boolean q_is_on_left = cover(root.left,q);
10         boolean p_is_on_left = cover(root.left,p);
11         
12         //分立两边 
13         if(q_is_on_left!=p_is_on_left) return root;
14         
15         //在一边
16         else{
17             if(q_is_on_left)
18                 return LCAhelp(root.left,p,q);
19             else
20                 return LCAhelp(root.right,p,q);
21         }
22     }
23     private boolean cover(TreeNode root,TreeNode p){
24         //检查p是不是root的孙子
25 
26         if(root==null) return false;
27         if(root==p) return true;
28         return cover(root.left,p)||cover(root.right,p);
29     }
30 }

 

 

 

 

 

解题思路

  • Divide & Conquer 的思路
  • 如果root为空,则返回空
  • 如果root等于其中某个node,则返回root
  • 如果上述两种情况都不满足,则divide,左右子树分别调用该方法
  • Divide & Conquer中这一步要考虑清楚,本题三种情况
  • 如果leftright都有结果返回,说明root是最小公共祖先
  • 如果只有left有返回值,说明left的返回值是最小公共祖先
  • 如果只有�right有返回值,说明�right的返回值是最小公共祖先
236. Lowest Common Ancestor of a Binary Tree(最低公共祖先,难理解)

 

 

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q || root == NULL) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left != NULL && right != NULL) return root;
        else if(left != NULL && right == NULL) return left;
        else if (left == NULL && right != NULL) return right;
        else return NULL;
    }
};
zle1992

 

 

相关文章:

  • 2021-06-04
  • 2021-06-12
  • 2021-08-30
猜你喜欢
  • 2021-07-14
  • 2022-12-23
  • 2021-12-06
  • 2021-12-28
  • 2021-05-11
相关资源
相似解决方案