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

Lowest Common Ancestor III Lintcode

时间:2017-02-03 10:44:09      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:tco   alert   mono   view   help   not   roo   stc   没有   

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
Return null if LCA does not exist.

 Notice

node A or node B may not exist in tree.

Example

For the following binary tree:

  4
 / 3   7
   /   5   6

LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

这道题做得累死了。。。主要的点在于变换递归的位置,就会造成不同的后果,如果放在一开始,那么就会一直到null才停止递归。。。这道题是从下向上。而且要想到可以新建一个类。什么时候要新建什么时候不用目前还没有太掌握。。。另外class不要写public的,不然要单独放在名为class名的文件里。

class Result {
    boolean foundA;
    boolean foundB;
    TreeNode root;
    public Result(boolean a, boolean b, TreeNode root) {
        foundA = a;
        foundB = b;
        this.root = root;
    }
}

public class Solution {
    /**
     * @param root The root of the binary tree.
     * @param A and B two nodes
     * @return: Return the LCA of the two nodes.
     */
    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        Result rs = helper(root, A, B);
        if (rs.foundA && rs.foundB) {
            return rs.root;
        }
        return null;
    }
    public Result helper(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) {
            return new Result(false, false, null);
        }
        
        Result left = helper(root.left, A, B);
        Result right = helper(root.right, A, B);
        
        boolean a = left.foundA || right.foundA || root == A;
        boolean b = left.foundB || right.foundB || root == B;
        
        if (root == A || root == B) {
            return new Result(a, b, root);
        }
        if (left.root != null && right.root != null) {
            return new Result(a, b, root);
        }
        if (left.root != null) {
            return new Result(a, b, left.root);
        }
        if (right.root != null) {
            return new Result(a, b, right.root);
        }
        return new Result(a, b, null);
    }
}

 

需要回顾。。。

 

 

Lowest Common Ancestor III Lintcode

标签:tco   alert   mono   view   help   not   roo   stc   没有   

原文地址:http://www.cnblogs.com/aprilyang/p/6361968.html

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