思路
代码
用深度搜索的思想(好吧,前序、中序、后序都是深搜思想),保存寻找路径,看看找到2个节点的路径的重合部分,就可以找到最近公共祖先;
/**
* 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:
vector<TreeNode*> path;
vector<vector<TreeNode*>> result;
void travel(TreeNode* cur, TreeNode* target)
{
if(cur == NULL)
{
return;
}
// 中
if(cur->val == target->val)
{
result.push_back(path);
return;
}
// 左
if(cur->left)
{
path.push_back(cur->left);
travel(cur->left, target);
path.pop_back();
}
// 右
if(cur->right)
{
path.push_back(cur->right);
travel(cur->right, target);
path.pop_back();
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
int i, j, min_length;
path.push_back(root);
travel(root, q);
path.clear();
path.push_back(root);
travel(root, p);
/*
for(i = 0; i < result.size(); i++)
{
for(j = 0; j < result[i].size(); j++)
{
cout << result[i][j]->val << ", ";
}
cout << endl;
}*/
// cout << "result[0].size() : " << result[0].size() << endl;
// cout << "result[1].size() : " << result[1].size() << endl;
min_length = min(result[0].size(), result[1].size());
for(i = 0; i < min_length; i++)
{
if(result[0][i]->val == result[1][i]->val)
{
continue;
}
else
{
break;
}
}
// cout << "i : " << i << "result[0][i] : " << result[0][i]->val;
return result[0][i-1];
}
};
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » [力扣题解] 236. 二叉树的最近公共祖先
发表评论 取消回复