【力扣hot100题】(048)二叉树的最近公共祖先

依旧只会用递归+栈。

栈记录当前遍历的节点,如果有一个节点已经被找到,则不往栈中添加新节点,并且每次回溯删除栈顶节点,每次回溯判断另一个节点有没有在栈顶节点的右边。

cpp 复制代码
/**
 * 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:
    stack<TreeNode*> record;
    bool search_p=0;
    bool search_q=0;
    TreeNode* result;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root==nullptr) return result;
        if(result!=nullptr) return result;
        if(!(search_p||search_q)) record.push(root);
        if(root==p) search_p=1;
        if(root==q) search_q=1;
        if(search_p&&search_q) result=record.top();
        if(result) return result;
        lowestCommonAncestor(root->left,p,q);
        lowestCommonAncestor(root->right,p,q);
        if(record.top()==root) record.pop();
        return result;
    }
};

不过写完一提交,看着这个时空复杂度的击败比例感觉它仿佛在告诉我什么......

答案用的也是递归,不过它的时空复杂度比我的低了好多TT明明都是遍历每一个节点,为什么会变成这样..................

cpp 复制代码
/**
 * 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* result;
    bool exist(TreeNode* root,TreeNode* p,TreeNode* q){
        if(root==nullptr) return 0;
        bool l=exist(root->left,p,q);
        bool r=exist(root->right,p,q);
        if((l&&r)||(root==p&&l)||(root==q&&r)||(root==p&&r)||(root==q&&l)) result=root;
        return l||r||(root==p)||(root==q);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        exist(root,p,q);
        return result;
    }
};
相关推荐
文丑颜不良啊41 分钟前
LeetCode2021~2040题目解析
java·leetcode
Yuzhiyuxia2 小时前
【AI Agent面试系列】上下文管理1
人工智能·面试·职场和发展
闻缺陷则喜何志丹3 小时前
【C++特性】四种类型转
c++·算法·类型转换
喵本喵叁肆3 小时前
用 Boosting 把弱隐私算法炼成强隐私算法(英文原题:Boosting and Differential Privacy (FOCS 2010))
算法·集成学习·boosting
青梅味猪大肠3 小时前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统
CoderYanger3 小时前
Java EE 进阶:8.MyBatis 操作数据库(入门)(第一弹)
java·数据库·spring·面试·职场和发展·java-ee·mybatis
其实防守也摸鱼18 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt19 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表