Lowest Common Ancestor III java 走地牙

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
/*
添加一个existA 和existB 用于表示是否找到A和B;
结果判断是 如果都找到了就return结果,没找到则return null;
*/

public class Solution {
    /*
     * @param root: The root of the binary tree.
     * @param A: A TreeNode
     * @param B: A TreeNode
     * @return: Return the LCA of the two nodes.
     */
    private boolean existA = false, existB = false;
    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        // write your code here
        if(root == null) return null;
        TreeNode result = helper(root, A, B);
        if(existA && existB) return result;
        return null;
    }
    
    public TreeNode helper(TreeNode root, TreeNode A, TreeNode B) {
        if(root == null) return null;
        
        TreeNode left = helper(root.left, A, B);
        TreeNode right = helper(root.right, A, B);
        
        if(root == A || root == B) {
            if(root == A) existA = true;
            if(root == B) existB = true;
            return root;
        }
        if(left != null && right != null) return root;
        if(left != null) return left;
        if(right != null) return right;
        return null;
    }
}

你可能感兴趣的:(刷题,CTCI)