236. Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:茉莉茶软化宫颈 知乎 编辑:程序博客网 时间:2024/06/11 04:29
超时了,amazing,主要是存储路径耗费大量的时间,要是能倒着走就好了。
/** * 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: void func(TreeNode* root, TreeNode* p, TreeNode* q,vector<TreeNode*>& resultP,vector<TreeNode*>& resultQ,vector<TreeNode*>& temp) { if(root==NULL) return; else { temp.push_back(root); if(resultP.size()==0&&root==p) resultP=temp; if(resultQ.size()==0&&root==q) resultQ=temp; if(resultP.size()!=0&&resultQ.size()!=0) return; if(root->left!=NULL) func(root->left,p, q,resultP,resultQ,temp); if(root->right!=NULL) func(root->right,p, q,resultP,resultQ,temp); temp.pop_back(); } } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode*> resultP; vector<TreeNode*> resultQ; vector<TreeNode*> temp; func(root,p,q,resultP,resultQ,temp); int index=0; while(index<min(resultP.size(),resultQ.size())) { if(resultP[index]==resultQ[index]) index++; else break; } return resultP[index--]; }};
后来试着另一种方式,只是保存其深度和值,最后再找,但是如果保存int,最多支持32层。。。。之后就越界了。。。尴尬。
参考了discuss,照着它的例子写出来类似的代码,amazing,厉害了我的哥。。。
/** * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL||root==p||root==q) return root; TreeNode* left=lowestCommonAncestor(root->left, p, q); TreeNode* right=lowestCommonAncestor(root->right, p, q); if(left!=NULL&&right!=NULL) return root; else if(left==NULL&&right!=NULL) return right; else if(left!=NULL&&right==NULL) return left; else return NULL; }};
0 0
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- CSS权值
- 【android知识必备】内存泄漏全解析,从此拒绝ANR,让OOM远离你的身边,跟内存泄漏say byebye【转】
- 【大话数据结构】——-线性表之链式存储
- FFMPEG 最简滤镜filter使用实例(实现视频缩放,裁剪,水印等)
- js 限制IE 文件上传大小
- 236. Lowest Common Ancestor of a Binary Tree
- Java 中的Monitor是什么意思?
- python爬虫正则表达式之处理换行符以及其他
- 关于#和##
- 天梯赛练习——输出GPLT
- 北航计算机机试08旋转矩阵
- vector《c++prime》
- AndroidStudio 2.2版本下的 单元测试 学习 一
- GitHub本地环境的配置