Lowest Common Ancestor(LCA)
2015-05-28 21:28
309 查看
1.是二叉搜索树
2.不是二叉搜索树,是二叉树
2.1有父指针
分别从两个结点出发,得到两个到根结点的单向链表,转换为求两个单向链表的第一个公共结点。
2.2没有父指针
(1)http://zhedahht.blog.163.com/blog/static/25411174201081263815813/
(2)
(3)Tarjan算法
(4)转换为RMQ问题
/article/8684743.html
3.不是二叉树,是树
struct TreeNode { int val; TreeNode *left,*right; }; TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2) { while(true) { if(root->val>p1->val&&root->val>p2->val)root=root->left; else if(root->val<p1->val&&root->val<p2->val)root=root->right; else return root; } }
2.不是二叉搜索树,是二叉树
2.1有父指针
分别从两个结点出发,得到两个到根结点的单向链表,转换为求两个单向链表的第一个公共结点。
2.2没有父指针
(1)http://zhedahht.blog.163.com/blog/static/25411174201081263815813/
(2)
TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2) { if(!root||root==p1||root==p2)return root; TreeNode *left=LCA(root->left,p1,p2); TreeNode *right=LCA(root->right,p1,p2); if(left&&right)return root; else if(left)return left; else if(right)return right; else return NULL; }
(3)Tarjan算法
(4)转换为RMQ问题
/article/8684743.html
3.不是二叉树,是树
struct TreeNode { int val; vector<TreeNode *>children; }; bool dfs(TreeNode *root,TreeNode *&p,vector<TreeNode *> &path) { if(!root)return false; path.push_back(root); if(root==p)return true; for(vector<TreeNode *>::iterator i=root->children.begin();i!=root->children.end();++i) { if(dfs(*i,p,path))return true; } path.pop_back(); return false; } TreeNode *LCA(TreeNode *root,TreeNode *p1,TreeNode *p2) { if(!root||!p1||!p2)return NULL; vector<TreeNode *> path1,path2; dfs(root,p1,path1); dfs(root,p2,path2); TreeNode *res; for(int i=0;i<path1.size()&&i<path2.size();++i) { if(path1[i]==path2[i])res=path1[i]; else break; } return res; }
相关文章推荐
- 互联网女皇”Mary Meeker 2015互联网趋势报告说了些什么
- 大
- BTrace
- JavaScript-回调函数
- destoon手机版去版权
- 第二阶段冲刺10
- 站立会议 第八天
- 插入排序
- 如何在开发IOS项目时获取当前项目的名称和版本号
- 日拱一卒(六十一)
- Pareto
- RaspberryPi上检测FreeSWITCH状态及启动FreeSWITCH
- intellij ctrl+alt+shift+u
- 重启VirtualBox里面的系统提示VT-x features locked or unavailable in MSR错误
- 树的子结构
- Next Permutation&&Permutation Sequence
- LVS NAT模型配置示例
- ACL权限
- HDU-1506
- WCF安全3-Transport与Message安全模式