zoukankan      html  css  js  c++  java
  • 236. Lowest Common Ancestor of a Binary Tree

    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;
        }
    };
    
  • 相关阅读:
    JQuery实现数组移除指定元素
    美团酒旅面经
    搜狗一面
    360面经
    头条面经
    搜狐笔试题
    kolakoski序列
    函数的节流
    隐藏元素的几种方法
    移动端适配与响应式布局
  • 原文地址:https://www.cnblogs.com/ToRapture/p/12674502.html
Copyright © 2011-2022 走看看