【力扣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;
    }
};
相关推荐
এ᭄画画的北北2 小时前
力扣-283.移动零
算法·leetcode
程序员三藏4 小时前
软件测试之单元测试
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
2501_924879365 小时前
口罩识别场景误报率↓79%:陌讯多模态融合算法实战解析
人工智能·深度学习·算法·目标检测·智慧城市
Christo35 小时前
TFS-2022《A Novel Data-Driven Approach to Autonomous Fuzzy Clustering》
人工智能·算法·机器学习·支持向量机·tfs
木木子99995 小时前
超平面(Hyperplane)是什么?
算法·机器学习·支持向量机·超平面·hyperplane
是乐谷6 小时前
阿里招AI产品运营
人工智能·程序人生·面试·职场和发展·产品运营·求职招聘
星空下的曙光7 小时前
React 虚拟 DOM Diff 算法详解,Vue、Snabbdom 与 React 算法对比
vue.js·算法·react.js
♞沉寂7 小时前
数据结构——双向链表
数据结构·算法·链表
大阳1237 小时前
数据结构2.(双向链表,循环链表及内核链表)
c语言·开发语言·数据结构·学习·算法·链表·嵌入式
CUC-MenG8 小时前
2025牛客多校第六场 D.漂亮矩阵 K.最大gcd C.栈 L.最小括号串 个人题解
c语言·c++·算法·矩阵