跳转至

236.二叉树的最近公共祖先 (Medium)*

题目描述*

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

示例*

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

输出: 3

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

输出: 5

代码*

不像上一个是有序的,这个只能遍历。

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

最后更新: July 23, 2022