[LeetCode] Lowest Common Ancestor of a Binary Tree
2015-07-25 18:57
591 查看
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes
5and
1is
3.
Another example is LCA of nodes
5and
4is
5,
since a node can be a descendant of itself according to the LCA definition.
解题思路:
这道题的意思是求出二叉树任何两点的最低公共节点。与二分查找树的不同是,这个查找并没有规律,只能暴力法进行。
解法一:
递归法。倘若p, q都在root的左孩子树中,则令root=root->left。倘若p, q都在root的右孩子树种,则令root=root->right。否则,返回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) {
if(root==NULL){
return NULL;
}
if(isInTree(root->left, p) && isInTree(root->left, q)){
return lowestCommonAncestor(root->left, p, q);
}else if(isInTree(root->right, p) && isInTree(root->right, q)){
return lowestCommonAncestor(root->right, p, q);
}else{
return root;
}
}
bool isInTree(TreeNode* root, TreeNode* p){
if(root==NULL){
return false;
}
return root == p || isInTree(root->left, p) || isInTree(root->right, p);
}
};解法二:
可以先求出p,q到根节点的路径,然后找到路径中第一个相同的节点。
/**
* 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){
return NULL;
}
if(p==q){
return p;
}
vector<TreeNode*> pPath;
vector<TreeNode*> qPath;
getPath(root, p, pPath);
getPath(root, q, qPath);
int i = pPath.size() - 1;
int j = qPath.size() - 1;
while(i>=0 && j>=0){
if(pPath[i] == qPath[j]){
i--;
j--;
}else{
return pPath[i+1];
}
}
return pPath[i+1];
}
bool getPath(TreeNode* root, TreeNode* p, vector<TreeNode*>& pPath){
if(root==NULL){
return false;
}
if(root==p){
pPath.push_back(root);
return true;
}
if(getPath(root->left, p, pPath) || getPath(root->right, p, pPath)){
pPath.push_back(root);
return true;
}
return false;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解