lc 二叉树的最近公共祖先

链接:https://leetcode-cn.com/submissions/detail/73071277/

代码:

/**
 * 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(!root) return nullptr;
        if(root->val == p->val || root->val == q->val) return root;
        
        TreeNode* lson = lowestCommonAncestor(root->left, p, q);
        TreeNode* rson = lowestCommonAncestor(root->right, p, q);
        
        if(!lson) return rson;
        if(!rson) return lson;
        if(lson && rson) return root;
        return nullptr;
    }
};
View Code

代码:递归,只有两个子树都出现 p,q,他们的 root 才是答案。如果左子树没有,则返回右子树,反之亦然,这个是比较难想,可以理解为是为了后序遍历。

posted on 2020-05-25 00:59  FriskyPuppy  阅读(145)  评论(0编辑  收藏  举报

导航