LeetCode 235. 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).”
  • Example :
    这里写图片描述
  • 地址

问题分析

  • 在一棵二叉搜索树上找两个节点的最近公共祖先,必须利用二叉搜索树的性质:左子树节点全部小于根节点,右子树节点全部大于跟节点,并且左右子树又是二叉搜索树。
  • 分三种情况讨论
    • 两节点值小于根节点值,那么最近公共祖先一定在左子树中
    • 两节点值大于根节点值,那么最近公共祖先一定在右子树中
    • 其他情况,最近公共祖先是根节点

代码实现

  • 递归
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == null || q == null) {
            return null;
        }
        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;
        }
    }
  • 迭代
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == null || q == null) {
            return null;
        }
        TreeNode pRoot = root;
        while(true) {
            if (p.val < pRoot.val && q.val < pRoot.val) {
                pRoot = pRoot.left;
            }else if (p.val > pRoot.val && q.val > pRoot.val) {
                pRoot = pRoot.right;
            }else {
                return pRoot;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值