美文网首页
leetcode 235二叉搜索树

leetcode 235二叉搜索树

作者: __hgb | 来源:发表于2019-06-08 09:02 被阅读0次
235.png
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if(p == null || q == null)
            throw new IllegalArgumentException("p or q can not be null.");

        if(root == null)
            return null;

        if(p.val < root.val && q.val < root.val)
            return lowestCommonAncestor(root.left, p, q);
        if(p.val > root.val && q.val > root.val)
            return lowestCommonAncestor(root.right, p, q);

        assert p.val == root.val || q.val == root.val
                || (root.val - p.val) * (root.val - q.val) < 0;

        return root;
    }

相关文章

网友评论

      本文标题:leetcode 235二叉搜索树

      本文链接:https://www.haomeiwen.com/subject/sjgbxctx.html