Lowest Common Ancestor of a Binary Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T. that has both v and w as descendants (where we allow a node to be a descendant of itself).”

Divide and Conquer

Time Complexity
O(N)

思路

首先要先确定给的两个node是否都在tree里,如果都在tree里的话,就可以分成3种情况,第一种情况是两个节点是在公共祖先的左右两侧,第二种情况是都在树的左侧,第三种情况是都在树的右侧,如果是第二,第三种情况的话,公共祖先就在给定的两个点中比较上面的那一个。


如果转换成代码的话,从上往下走,base case分为3种,判断遇到了p就直接返回p,遇到q就直接返回q,不用向下做了。如果left,right都不为空,就返回root自己;left,right哪一个不为空就返回哪个,整个recursion做完就可以得到LCA。

代码

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) return null;
    if(root == p) return p;
    if(root == q) return q;
    
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    
    if(left != null && right != null) return root;
    return left != null ? left : right;
}

Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

Divide and Conquer

Time Complexity
O(N)

思路

LCA肯定是落在p,q两个点之间的,或者是p, q其中一个点,在BST中,这就等于LCA的大小一定是在p.val,q.val之间的,或者等于p.val, q.val。从上往下走,遇到的第一个p,q之间的或者是p,q其中一个,一定是LCA,不用再继续往下走了。如果cur root,比p,q中的都大的话,cur往左走,比p,q中的都小的话cur往右走。

代码

Recursive

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) return null;
    
    if(root.val > p.val && root.val > q.val){
        return lowestCommonAncestor(root.left, p, q);
    }
    if(root.val < p.val && root.val < q.val){
        return lowestCommonAncestor(root.right, p, q);
    }
    return root;
}

Non-Recursive

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null) return null;
    
    while(true){
        if(root.val > p.val && root.val > q.val){
            root = root.left;
        }else if(root.val < p.val && root.val < q.val){
            root = root.right;
        }else break;
    }
    
    return root;
}

Lowest Common Ancestor of a Binary Tree With Parent Node

思路

如果有Parent指针的话,这就又变成Linkedlist求intersection了


annielulu
5 声望5 粉丝