一颗普通的二叉树,如何寻找两个节点的最低公共祖先(发现的一个与算法无关的引用问题)
2015-08-12 14:23
633 查看
算法很简单:先通过DFS深度优先遍历二叉树,找到两个节点的路径(从root开始),保存两个路径,然后比较两个路径中相同位置的节点是否是同一个节点。如果是最后一个相同的节点,那么就是最低公共祖先。
先上代码吧,/**
* 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) {
//首先前序遍历二叉树,得到从root到p,q的路径
vector<TreeNode*> rode1;
vector<TreeNode*> rode2;
FindPath(root, p, rode1);
FindPath(root, q, rode2);
TreeNode* result;
for(int i=0 ;i<min(rode1.size(),rode2.size());++i){
if(rode1[i]==rode2[i])
result = rode1[i];
}
return result;
}
bool FindPath(TreeNode*root, TreeNode* end, vector<TreeNode*> path)
{
if(root == NULL)
return false;
if(root== end)
{
path.push_back(root);
return true;
}
path.push_back(root);
bool found = false;
if(!found)
found = FindPath(root->left, end, path);
if(!found)
found = FindPath(root->right, end, path);
if(!found)
path.pop_back();
return found;
}
};
这是我最开始的代码,提交到leetcode的时候显示内存不够。最后发现问题出在标红的那一行,传递vetcor的时候传递用得是传值,最后会把整个vector复制一遍。当把vector改为传引用,即&path后accept.其实以前就知道如果传递大量数据作为形参的时候应该用引用&,但是还是在写代码的时候忘记了。
先上代码吧,/**
* 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) {
//首先前序遍历二叉树,得到从root到p,q的路径
vector<TreeNode*> rode1;
vector<TreeNode*> rode2;
FindPath(root, p, rode1);
FindPath(root, q, rode2);
TreeNode* result;
for(int i=0 ;i<min(rode1.size(),rode2.size());++i){
if(rode1[i]==rode2[i])
result = rode1[i];
}
return result;
}
bool FindPath(TreeNode*root, TreeNode* end, vector<TreeNode*> path)
{
if(root == NULL)
return false;
if(root== end)
{
path.push_back(root);
return true;
}
path.push_back(root);
bool found = false;
if(!found)
found = FindPath(root->left, end, path);
if(!found)
found = FindPath(root->right, end, path);
if(!found)
path.pop_back();
return found;
}
};
这是我最开始的代码,提交到leetcode的时候显示内存不够。最后发现问题出在标红的那一行,传递vetcor的时候传递用得是传值,最后会把整个vector复制一遍。当把vector改为传引用,即&path后accept.其实以前就知道如果传递大量数据作为形参的时候应该用引用&,但是还是在写代码的时候忘记了。
相关文章推荐
- 机器学习算法需要注意的一些问题(二)
- 黑马程序员------------------java基础--------------------集合
- C++ 简介
- SAS JAVA 连接操作
- 机器人跳跃问题
- 去除GHOST版系统自带的2345流氓软件
- Spring注解和配置方式
- 【Xamarin开发 Android 系列 8】 创建一个Json读取数据应用(上)
- CodeIgniter HMVC 扩展
- 比较重要的开源工具
- Windows下批处理文件(.bat)的使用
- Chapter 10 手势 iOS 8 -Swift Programming cookBook 读书笔记
- jQuery_统计图插件-flot
- HDU 3308 LCIS
- Android Api Demos登顶之路(三十一)Alarm Controller
- Windows下批处理文件(.bat)的使用
- MFC radio button 设置默认选中
- 如何掌握程序语言(王垠)
- tomcat 配置httponly
- IOS开发中实现UITableView按照首字母将集合进行检索分组