题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

直接递归,思路清晰
class Solution {
public:
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        int Min = min(p, q);
        int Max = max(p, q);
        if (root->val > Min && root->val > Max) {
            return lowestCommonAncestor(root->left, p, q);
        }
        if (root->val < Min && root->val < Max) {
            return lowestCommonAncestor(root->right, p, q);
        }
        return root->val;
    }
};


#今天让我开心的事#
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务