首页 > 其他 > 详细

236. Lowest Common Ancestor of a Binary Tree

时间:2020-04-10 17:26:51      阅读:61      评论:0      收藏:0      [点我收藏+]

236. Lowest Common Ancestor of a Binary Tree

If we can find two subtrees of root such that both of them has target, then root is the LCA of p and q.
If there is exactly one subtree of root having target and root itself has target, then root is the LCA of p and q too.

/**
 * 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 *ans;
    bool hasTarget(TreeNode *root, TreeNode *p, TreeNode *q) {
        if (root == nullptr) return false;
    
        bool left = hasTarget(root->left, p, q);
        bool right = hasTarget(root->right, p, q);
        bool mid = root == p || root == q;
        
        if ((left && right) || (left && mid) || (mid && right)) {
            ans = root;
        }
        
        return left || right || mid;
    }
    
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        ans = nullptr;
        hasTarget(root, p, q);
        return ans;
    }
};

236. Lowest Common Ancestor of a Binary Tree

原文:https://www.cnblogs.com/ToRapture/p/12674502.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!