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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章