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

3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)

时间:2018-03-03 12:14:41      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:https   span   com   case   bin   post   binary   between   调用   

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 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {   
        if(root == null){
            return null;
        }
        if(root == p || root == q){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left != null && right != null){
            return root;
        }
        if(left != null){
            return left;
        }
        if(right != null){
            return right;
        }
        return null;
    }
}

这道题在235基础上取消了BST的限制,所以我们无法通过比较值的大小来进行剪枝,那么这道题的思路就是用一般的recursion来做。

明确一点,如果某个顶点是我们所要的结果,则有且只有一种情况满足条件:该node左树,右树,分别有p,q之一。(*)

某个node左树(或右树)有p 和 q,则这个node一定不是最小公共node。

基于此,我们的recursion就写出来啦

1.base case: null

2. subproblem: 左树,右树

2.recursion rule: 如果看到了p,q,返回。否则调用subproblem。

如果左右都不是null,说明左右各有一p,q,满足(*),返回当前root

如果左不为空,返回左

如果右不为空,返回右

 

 

 

 

3.2 Lowest Common Ancestor of a Binary Tree(LeetCode 236)

标签:https   span   com   case   bin   post   binary   between   调用   

原文地址:https://www.cnblogs.com/juanqiuxiaoxiao/p/8495984.html

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