Leetcode - Lowest Common Ancestor of a Binary Search Tree

Question

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.

Java Code

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    TreeNode LCA = root;
    int pVal = p.val;
    int qVal = q.val;
    int value = root.val;
    while(true) {//LCA必定存在,while不会是死循环
        value = LCA.val;
        if(pVal < value && qVal < value)//如果两个节点都位于当前节点的左子树中,继续在左子树中查找
            LCA = LCA.left;
        else if(pVal > value && qVal > value)//如果两个节点都位于当前节点的右子树中,继续在右子树中查找
            LCA = LCA.right;
        else//如果有一个节点等于当前节点,或者两个节点位于当前节点的不同子树中,则该节点就是LCA
            return LCA;
    }
}

你可能感兴趣的:(LeetCode,tree,LCA)