Lowest Common Ancestor III Lintcode

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);
    }
}

 

需要回顾。。。

 

 

posted @ 2017-02-03 06:18  璨璨要好好学习  阅读(298)  评论(0编辑  收藏  举报