Lowest Common Ancestor of a Binary Tree
2015-09-05 20:41
239 查看
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == p || root == q) return root;
TreeNode *L = lowestCommonAncestor(root->left, p, q);
TreeNode *R = lowestCommonAncestor(root->right, p, q);
if (L && R) return root; // if p and q are on both sides
return L ? L : R; // either one of p,q is on one side OR p,q is not in L&R subtrees
}
};
还是主要判断在两边还是在一边。
下面是自己的办法,超时了,先用find函数判断在哪边,在返回,其实多此一举。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return root;
if(root==p||root==q) return root;
if((find(root->left,p)&&find(root->right,q))||(find(root->left,q)&&find(root->right,p))) return root;
if(find(root->left,p)&&find(root->left,q)) return lowestCommonAncestor(root->left,p,q);
if(find(root->right,p)&&find(root->right,q)) return lowestCommonAncestor(root->right,p,q);
}
bool find(TreeNode* root, TreeNode* p)
{
if(root==NULL) return false;
if(root==p) return true;
else return find(root->left,p)||find(root->right,p);
}
};
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == p || root == q) return root;
TreeNode *L = lowestCommonAncestor(root->left, p, q);
TreeNode *R = lowestCommonAncestor(root->right, p, q);
if (L && R) return root; // if p and q are on both sides
return L ? L : R; // either one of p,q is on one side OR p,q is not in L&R subtrees
}
};
还是主要判断在两边还是在一边。
下面是自己的办法,超时了,先用find函数判断在哪边,在返回,其实多此一举。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return root;
if(root==p||root==q) return root;
if((find(root->left,p)&&find(root->right,q))||(find(root->left,q)&&find(root->right,p))) return root;
if(find(root->left,p)&&find(root->left,q)) return lowestCommonAncestor(root->left,p,q);
if(find(root->right,p)&&find(root->right,q)) return lowestCommonAncestor(root->right,p,q);
}
bool find(TreeNode* root, TreeNode* p)
{
if(root==NULL) return false;
if(root==p) return true;
else return find(root->left,p)||find(root->right,p);
}
};
相关文章推荐
- QQ聊天
- strace 工具
- Eclipse添加Android项目工程后res文件夹下layout/values/drawable文件不可见
- 在多线程/进程环境下,计算系统的总响应时间
- 六款值得推荐的android(安卓)开源框架简介
- 软工视频——软工概论
- Apache Camel的sample的简单示例
- Linux 命令[4]:pwd,date
- 日志文件名更新
- PHP博客
- java下管道流 PipedOutputStream 与PipedInputStream
- 摄影测量后方交会-前方交会(C#)
- jsp分页代码
- UIGestureRecognizer
- Android 的消息队列模型
- Wait和Pulse
- 苹果联合创始人爆料:初代苹果电脑非乔布斯设计
- df du 区别
- 算法----优先队列
- 尽量避免官司缠身