【力扣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;
    }
};
相关推荐
草履虫建模1 天前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
naruto_lnq1 天前
分布式系统安全通信
开发语言·c++·算法
Jasmine_llq1 天前
《P3157 [CQOI2011] 动态逆序对》
算法·cdq 分治·动态问题静态化+双向偏序统计·树状数组(高效统计元素大小关系·排序算法(预处理偏序和时间戳)·前缀和(合并单个贡献为总逆序对·动态问题静态化
爱吃rabbit的mq1 天前
第09章:随机森林:集成学习的威力
算法·随机森林·集成学习
(❁´◡`❁)Jimmy(❁´◡`❁)1 天前
Exgcd 学习笔记
笔记·学习·算法
YYuCChi1 天前
代码随想录算法训练营第三十七天 | 52.携带研究材料(卡码网)、518.零钱兑换||、377.组合总和IV、57.爬楼梯(卡码网)
算法·动态规划
不能隔夜的咖喱1 天前
牛客网刷题(2)
java·开发语言·算法
VT.馒头1 天前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
进击的小头1 天前
实战案例:51单片机低功耗场景下的简易滤波实现
c语言·单片机·算法·51单片机
咖丨喱1 天前
IP校验和算法解析与实现
网络·tcp/ip·算法