Files
leetcode-master/problems/0236.二叉树的最近公共祖先.md
youngyangyang04 1a0da92dcc Update
2020-09-28 11:58:12 +08:00

744 B

链接

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

思路

与其说是递归,不如说是回溯。(要好好讲讲回溯)

如果左孩子出现在左子树,右孩子出现在右子树,那么该节点为最近公共祖先。

最后如果

C++代码

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

        if (left == NULL) return right;
        return left;
    }
};