235. 二叉搜索树的最近公共祖先 【根据二叉搜索树特点分类】

43 阅读1分钟

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

每日链接

image.png

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # 二叉搜索树 !!!
        # 当前结点的值 > p 和 q 的值, p 和 q 都在 左子树, 递归 左子树

        if p.val < root.val and q.val < root.val: # 都在左子树
            return self.lowestCommonAncestor(root.left, p, q)
        elif p.val > root.val and q.val > root.val: # 都在右子树
            return self.lowestCommonAncestor(root.right, p, q)
        return root 

image.png

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

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