算法很简单:先通过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.其实以前就知道如果传递大量数据作为形参的时候应该用引用&,但是还是在写代码的时候忘记了。