剑指 Offer 68 - I 二叉搜索树的最近公共祖先

Tag: 剑指-Offer Posted on 2022-02-28 11:35:17 Edited on 2022-02-28 11:35:17 Views: 150

概述

https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

递归法

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

未经允许,禁止转载,本文源站链接:https://iamazing.cn/