[LeetCode] Lowest Common Ancestor of a Binary Search Tree

时间:2022-08-26 10:04:59

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

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).”

Given the following binary search tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

Example 1:

Input: root, p = 5, q = 1
Output: 3
Explanation: The LCA of of nodes 5 and 1 is 3.

Example 2:

Input: root, p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
             according to the LCA definition.

求二叉搜索树的最低公共祖先结点

根据二叉搜索树的性质:位于左子树的结点都比父结点小,位于右子树的结点都比父结点大。

两个结点的最低公共祖先:指两个结点都出现在某个结点的子树中,我们可以从根结点出发遍历一棵树,每遍历一个结点判断两个输入是否在其子树中,如果在其子树中,分别遍历它的所有结点并判断两个输入结点是否在其子树中。直到找到第一个结点,它的子树中同时包括两个输入结点但它的子结点却没有。那么该结点就是最低的公共祖先。

递归

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == nullptr || p == nullptr || q == nullptr)
            return root;
        if (max(p->val, q->val) < root->val)
            return lowestCommonAncestor(root->left, p, q);
        else if (min(p->val, q->val) > root->val)
            return lowestCommonAncestor(root->right, p, q);
        else
            return root;
    }
};

迭代

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || !p || !q)
            return nullptr;
        int left = p->val, right = q->val;
        while (root)
        {
            int target = root->val;
            if (target > left && target > right)
                root = root->left;
            else if (target < left && target < right)
                root = root->right;
            else
                break;
        }
        return root;
    }
};