LCA---Lowest common ancestor

在root爲根的二叉樹中找A,B的LCA:
若是找到了就返回這個LCA
若是隻碰到A,就返回A
若是隻碰到B,就返回B
若是都沒有,就返回nullnode

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

public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param A and B: two nodes in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2) {
        
         //三種狀況: 都在左子樹中, 都在右子樹中, 左右分別
        //在二叉樹的左右子樹找node1和node2, 找到及返回, 根據left和right是否存在內容決定最低公共祖先
        if (root == null || root == node1 || root == node2){
            return root;
        }
        
        TreeNode left = lowestCommonAncestor(root.left, node1, node2);
        TreeNode right = lowestCommonAncestor(root.right, node1, node2);
        
        if (left != null && right != null){
            return root;
        }
        
        if (left != null){
            return left; 
        }
        if (right != null){
            return right;
        }
        else{
            return null;
        }
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        //終止條件, 找到node1或者node2,或者到null node, 就return
        // if (root == null || root == node1 || root == node2) {
        //     return root;
        // }
        
        // Divide (在left child和right child裏面找node1和2)
        // TreeNode left = lowestCommonAncestor(root.left, node1, node2);
        // TreeNode right = lowestCommonAncestor(root.right, node1, node2);
        
        // Conquer  
        // if (left != null && right != null) {
        //     return root;
        // } 
        // if (left != null) {
        //     return left;
        // }
        // if (right != null) {
        //     return right;
        // }
        // return null;            //當left sub和right sub都沒有n1或n2
    }
}
相關文章
相關標籤/搜索