Tree——No.236 Lowest Common Ancestor of a Binary Tree

No.236 Lowest Common Ancestor of a Binary Tree

Problem:

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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Explanation:

找出二叉搜索树两个结点的最近公共祖先。

My Thinking:

My Solution:

Optimum Thinking:

  1. 使用递归,利用二叉搜索树左小右大的性质,若p和q都小(大)于当前结点,则对当前结点的左(右)子树进行递归,如果p和q都不同时大于或小于当前结点,说明两个结点从当前结点开始分叉,即当前结点就是最小祖宗。
  2. 对root进行迭代,和递归条件一样,迭代到p和q都不同时大于或小于当前结点。
  3. 网友更简洁的答案。

Optimum Solution:

(1)

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

(2)

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

(3)

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    while ((root.val - p.val) * (root.val - q.val) > 0)//p、q同时大于或小于root
        root = p.val < root.val ? root.left : root.right;
    return root;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值