235. Lowest Common Ancestor of a Binary Search Tree | Java最短代码实现

原题链接: 235. Lowest Common Ancestor of a Binary Search Tree

【思路】

本题拓展:Lowest Common Ancestor of a Binary Tree 给定二叉搜索树的好处是除了叶子节点外,左子树的所有节点小于根节点,右子树的所有节点大于根节点。利用这一特性,当

(root.val - p.val) * (root.val -q.val)不大于0时,p,q节点必然在root两侧,直接返回即可,否则往左或右子树继续递归:

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if ((root.val - p.val) * (root.val - q.val) <= 0) return root;
        if (root.val > p.val) return lowestCommonAncestor(root.left, p, q);
        else return lowestCommonAncestor(root.right, p, q);
    }
27 / 27  test cases passed. Runtime: 11 ms  Your runtime beats 12.65% of javasubmissions.
欢迎优化!

你可能感兴趣的:(递归,tree,search,binary)