当前位置: 首页> 健康> 科研 > 杭州疫情最新信息_天津市建设工程信息网站_国内永久免费云服务器_西安百度关键词包年

杭州疫情最新信息_天津市建设工程信息网站_国内永久免费云服务器_西安百度关键词包年

时间:2025/8/24 2:16:24来源:https://blog.csdn.net/s478527548/article/details/146988816 浏览次数:0次
杭州疫情最新信息_天津市建设工程信息网站_国内永久免费云服务器_西安百度关键词包年

依旧只会用递归+栈。

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

/*** 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明明都是遍历每一个节点,为什么会变成这样………………

/*** 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;}
};

关键字:杭州疫情最新信息_天津市建设工程信息网站_国内永久免费云服务器_西安百度关键词包年

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: