236. Lowest Common Ancestor of a Binary Tree

Posted 张乐乐章

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

解题思路

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


 1 class Solution {
 2     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
 3         if(root ==null || p==root||q==root) return root;
 4         TreeNode lp = lowestCommonAncestor(root.left,p,q);
 5         TreeNode rp = lowestCommonAncestor(root.right,p,q);
 6         if(lp!=null&&rp!=null) return root;
 7         if(lp==null&&rp!=null) return rp;
 8         if(lp!=null&&rp==null) return lp;
 9         return null;
10     }
11 }

 

以上是关于236. Lowest Common Ancestor of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree