236. Lowest Common Ancestor of a Binary Tree(最低公共祖先,难理解)

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不在同一边,那就表示已经找到第一个公共祖先。

 class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(!cover(root,p)||!cover(root,q)) return null;
return LCAhelp(root,p,q);
}
private TreeNode LCAhelp(TreeNode root,TreeNode p,TreeNode q ){
if(root==null) return null;
if(root==p||root==q) return root;
boolean q_is_on_left = cover(root.left,q);
boolean p_is_on_left = cover(root.left,p); //分立两边
if(q_is_on_left!=p_is_on_left) return root; //在一边
else{
if(q_is_on_left)
return LCAhelp(root.left,p,q);
else
return LCAhelp(root.right,p,q);
}
}
private boolean cover(TreeNode root,TreeNode p){
//检查p是不是root的孙子 if(root==null) return false;
if(root==p) return true;
return cover(root.left,p)||cover(root.right,p);
}
}

解题思路

  • Divide & Conquer 的思路
  • 如果root为空,则返回空
  • 如果root等于其中某个node,则返回root
  • 如果上述两种情况都不满足,则divide,左右子树分别调用该方法
  • Divide & Conquer中这一步要考虑清楚,本题三种情况
  • 如果leftright都有结果返回,说明root是最小公共祖先
  • 如果只有left有返回值,说明left的返回值是最小公共祖先
  • 如果只有�right有返回值,说明�right的返回值是最小公共祖先
 class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root ==null || p==root||q==root) return root;
TreeNode lp = lowestCommonAncestor(root.left,p,q);
TreeNode rp = lowestCommonAncestor(root.right,p,q);
if(lp!=null&&rp!=null) return root;
if(lp==null&&rp!=null) return rp;
if(lp!=null&&rp==null) return lp;
return null;
}
}
上一篇:[代码审计]XiaoCms(后台任意文件上传至getshell,任意目录删除,会话固定漏洞)


下一篇:易优cms后台RCE以及任意文件上传漏洞