[LeetCode] Lowest Common Ancestor of a Binary Tree系列

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了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值