[二叉树BST]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).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

一个平衡二叉树,找到两个节点共同的最小root,root可以是其中某一个节点。
分析BST性质,必然左<中<右。所以只有三种可能:

  1. 左<= root <=右 那么返回root
  2. root < 左<右,那么root.left就是新的root继续比较。
  3. 左< 右< root,那么root.right是新的root。
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || p == null || q == null) return root;
        int left = (p.val < q.val)? p.val:q.val;
        int right = (p.val < q.val)? q.val:p.val;
             
        if(root.val >= left && root.val <= right) return root;
        if(root.val > right) return lowestCommonAncestor(root.left, p,q);
        return lowestCommonAncestor(root.right,p,q);
    }
}

你可能感兴趣的:([二叉树BST]235. Lowest Common Ancestor of a Binary Search Tree)