【力扣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;
    }
};
相关推荐
IT猿手32 分钟前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风33 分钟前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘1 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
㓗冽1 小时前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物1 小时前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀2 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马2 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀2 小时前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中2 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#