1、Lowest Common Ancestor of a Binary Search Tree

Total Accepted: 42225 Total Submissions: 111243 Difficulty: Easy

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

Total Accepted: 26458 Total Submissions: 95470 Difficulty: Medium

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的更多相关文章

  1. 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.每次更新的 ...

  2. 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 ...

  3. openerp学习笔记 视图继承(tree、form、search)

    支持的视图类型:form.tree.search ... 支持的定位方法:                  <notebook position="inside"> ...

  4. EasyUI –tree、combotree学习总结

    EasyUI –tree.combotree学习总结 一.   tree总结 (一).tree基本使用 tree控件是web页面中将数据分层一树形结构显示的. 使用$.fn.tree.defaults ...

  5. 主席树[可持久化线段树](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 ...

  6. 适用于zTree 、EasyUI tree、EasyUI treegrid

    #region          System.Text.StringBuilder b_appline = new System.Text.StringBuilder();        Syste ...

  7. 决策树(中)-集成学习、RF、AdaBoost、Boost Tree、GBDT

    参考资料(要是对于本文的理解不够透彻,必须将以下博客认知阅读): 1. https://zhuanlan.zhihu.com/p/86263786 2.https://blog.csdn.net/li ...

  8. 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. ...

  9. 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 ...

随机推荐

  1. JS闭包(一)

    闭包是指有权访问另一个函数作用域中的变量的函数. 创建闭包的常见方法:在一个函数内部创建另一个函数. 对彻底理解闭包,需要知道如何创建作用域链以及作用域链有什么作用的细节. 闭包的功能: 保存函数执行 ...

  2. java集合之Map_keySet_entrySet

    keySet()的使用:该方法返回的是一个key对象的Set<E>集合,通过该set集合的对象调用iterator方法返回一个迭代器,通过该迭代器可访问到set集合里面的key 再调用Ha ...

  3. mysql 复习与学习(二)数据库及表结构的创建删除

    mysql -h localhost -uroot -p123456 //连接数据库 show databases; //查看数据库 create database if not exists db_ ...

  4. Tomcat学习笔记 - 错误日志 - Tomcat安装版安装后第二次启动后闪退(转)-- javac不是内部或外部命令 -- 配置java环境教程

    如果安装成功并且安装完成第一次启动是成功的,第二次就闪退的话,原因之一是没有配置java的环境.在网上找的配制方法有很多错误,测试javac命令时候会提示不是内部或外部命令,找到一个正确的教程.如下, ...

  5. PHP API反射实例

    *反射是操纵面向对象范型中元模型的API,其功能十分强大,可帮助我们构建复杂,可扩展的应用.其用途如:自动加载插件,自动生成文档,甚至可用来扩充PHP语言.php反射api由若干类组成,可帮助我们用来 ...

  6. postgresql的psql命令

    1:不进入数据库而执行SQL命令,用参数-c 2:把SQL命令保存在一个外部文件中,用 -f 参数导入并执行 a1.txt文件内容 select * from student; 在shell中用如下命 ...

  7. [statsvn]-svn代码量统计

    用statasvn进行代码量统计的时候,第一步需要获取到项目的日志,但是我本机的svn1.4没有安装命令行,重新运行1.4的安装包也没有命令行的选项... 那就升级到最新的svn1.8好了,下载最新的 ...

  8. EF调用存储过程实例

    创建实体: public class User { public string UserID { get; set; } public string UserName { get; set; } pu ...

  9. Hbase深入学习(二) 安装hbase

    Hbase深入学习(二) 安装hbase This guidedescribes setup of a standalone hbase instance that uses the local fi ...

  10. iframe父子页面互调方法和属性

    1.iframe子页面调用 父页面js函数 子页面调用父页面函数只需要写上window.praent就可以了.比如调用a()函数,就写成: window.parent.a(); 子页面取父页面中的标签 ...