Lowest Common Ancestor of a Binary Search Tree、Lowest Common Ancestor of a Binary Search Tree
1、Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
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).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
/**
* 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->val >= min(p->val,q->val) && root->val <= max(p->val,q->val)) return root;
if(root->val >=max(p->val,q->val)) return lowestCommonAncestor(root->left,p,q) ;
else return lowestCommonAncestor(root->right,p,q);
}
};
2、Lowest Common Ancestor of a Binary Tree
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 5
and 1
is 3
. Another example is LCA of nodes 5
and 4
is 5
, since a node can be a descendant of itself according to the LCA definition.
方法1.
/**
* 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 == p || root == q || root == NULL) {
return root;
} TreeNode* left = lowestCommonAncestor(root->left ,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q); if(left==NULL && right==NULL){
return NULL;
} if(left!=NULL && right==NULL){
return left;
} if(right!=NULL && left == NULL){
return right;
} return root;
}
};
方法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 {
private:
bool getPath(TreeNode* root,TreeNode* node,list<TreeNode*>& list_path){
if(root==NULL){
return false;
} list_path.push_back(root); if(root == node) {
return true;
} bool in_left = getPath(root->left,node,list_path);
if(in_left){
return true;
} bool in_right = getPath(root->right,node,list_path); if(!in_right){
list_path.pop_back();
} return in_right;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
list<TreeNode*> list_path_p,list_path_q; bool list_path_p_exist = getPath(root,p,list_path_p);
bool list_path_q_exist = getPath(root,q,list_path_q); if(!list_path_p_exist && !list_path_q_exist){
return NULL;
} TreeNode* res = NULL;
while(list_path_p.front() == list_path_q.front()){
res = list_path_p.front();
list_path_p.pop_front();
list_path_q.pop_front();
} return res;
}
};
Lowest Common Ancestor of a Binary Search Tree、Lowest Common Ancestor of a Binary Search Tree的更多相关文章
- leetcode 108. Convert Sorted Array to Binary Search Tree 、109. Convert Sorted List to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree 这个题使用二分查找,主要要注意边界条件. 如果left > right,就返回NULL.每次更新的 ...
- 36. Construct Binary Tree from Inorder and Postorder Traversal && Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal OJ: https://oj.leetcode.com/problems/cons ...
- openerp学习笔记 视图继承(tree、form、search)
支持的视图类型:form.tree.search ... 支持的定位方法: <notebook position="inside"> ...
- EasyUI –tree、combotree学习总结
EasyUI –tree.combotree学习总结 一. tree总结 (一).tree基本使用 tree控件是web页面中将数据分层一树形结构显示的. 使用$.fn.tree.defaults ...
- 主席树[可持久化线段树](hdu 2665 Kth number、SP 10628 Count on a tree、ZOJ 2112 Dynamic Rankings、codeforces 813E Army Creation、codeforces960F:Pathwalks )
在今天三黑(恶意评分刷上去的那种)两紫的智推中,突然出现了P3834 [模板]可持久化线段树 1(主席树)就突然有了不详的预感2333 果然...然后我gg了!被大佬虐了! hdu 2665 Kth ...
- 适用于zTree 、EasyUI tree、EasyUI treegrid
#region System.Text.StringBuilder b_appline = new System.Text.StringBuilder(); Syste ...
- 决策树(中)-集成学习、RF、AdaBoost、Boost Tree、GBDT
参考资料(要是对于本文的理解不够透彻,必须将以下博客认知阅读): 1. https://zhuanlan.zhihu.com/p/86263786 2.https://blog.csdn.net/li ...
- Linux 常用命令1 pwd、ls、cd、tab、清屏、重定向、转义、管道、touch、mkdir、tree、cat、more、rmdir、rm、grep、help、man、history、find、cp、mv、tar、gz
版权声明:本文为博主引用文章,未经博主及作者允许不得转载. 声明: 涉及的命令:pwd.ls.cd.tab.清屏.重定向.转义.管道.touch.mkdir.tree.cat.more.rmdir. ...
- Stern-Brocot Tree、伪.GCD 副本
Stern-Brocot Tree.伪.GCD 副本 伪.GCD 问题 1:\(f(a,b,c,n) = \sum_{i=0}^{n} [\frac{ai+b}{c}]\) Case 1: \(a\g ...
随机推荐
- .Net Memory -- Windbg基本命令
命令 解释 .cls 清空命令窗口屏幕 .load dllfullpath 加载debugger扩展dll如SOS sosex psscor. .loadby dll moduleName 加载deb ...
- poj3159 Candies(差分约束)
转载请注明出处: http://www.cnblogs.com/fraud/ ——by fraud Candies Time Limit: 1500MS Memory Limit ...
- 火狐浏览器,hostadmin hosts文件访问权限不足
开始->附件->以管理员身份运行. cacls %windir%\system32\drivers\etc\hosts /E /G Users:W
- [C++程序设计]返回指针值的函数
定义指针函数的一般形式为 类型名 *函数名(参数表列); 例如 int *a(int x,int y);
- Ubuntu安装字体的方法
基本步骤如下: 1. 将要安装的字体放在一个文件夹下,以/home/UsrName/Download/Font为例 2.在终端中输入 sudo cp -r /home/UsrName/Download ...
- python笔记之调用系统命令
python笔记之调用系统命令 目前我使用到的python中执行cmd的方式有三种 使用os.system("cmd") 该方法在调用完shell脚本后,返回一个16位的二进制数, ...
- Python学习(四) Python数据类型:序列(重要)
插播一下,先了解一下Python的数据类型,Python现有的数据类型有好多,最重要的有列表.元组.字典 列表:我觉得可以对应java中的数组 list=['physics', 'chemistry' ...
- MVC WEB api 自动生成文档
最近在一直在用webapi做接口给移动端用.但是让我纠结的时候每次新加接口或者改动接口的时候,就需要重新修改文档这让我很是苦恼.无意中发现.webapi居然有自动生成文档的功能....真是看见了救星啊 ...
- ASP.NET MVC 4.0 学习4-Code First
之前我們需要用到的數據,通過添加Entity實體數據模型把數據庫中需要的Database拉到項目中如下圖, 而就是Code First就是相對於這種處理數據的方法而言的 Code First更加準確的 ...
- Kafka与Logstash的数据采集
Kafka与Logstash的数据采集 基于Logstash跑通Kafka还是需要注意很多东西,最重要的就是理解Kafka的原理. Logstash工作原理 由于Kafka采用解耦的设计思想,并非原始 ...