码迷,mamicode.com
首页 > 其他好文 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2018-02-05 23:16:33      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:example   another   ==   strong   turn   get   amp   解题思路   fine   

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

标签:example   another   ==   strong   turn   get   amp   解题思路   fine   

原文地址:https://www.cnblogs.com/zle1992/p/8419511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!