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. MVC 界面开发

    1.什么是设计模式 mvc只是其中一种,对某一类具体问题,总结出来的一套最优的解决方案 1.MVC: 1.Model(模型)     View(视图)    Controller(控制器) 的缩写 M ...

  2. Dapper simplecrud的使用

    为了方便Dapper操作可以使用Dapper的相关扩展dapper simplecrud. 1.首先点击管理NuGet

  3. web前端中实现多标签页切换的效果

    在这里,实现多标签页效果的方法有两个,一个是基于DOM的,另一个是基于jquery的,此次我写的是一个对于一个电话套餐的不同,显示不同的标签页 方法一: 首先,我们要把页面的大体框架和样式写出来,ht ...

  4. Install cv2.so for Anaconda

    sudo apt-get install python-opencv cp /usr/lib/python2.7/dist-packages/cv2.so /opt/anaconda/lib/pyth ...

  5. spring2.5IOC控制反转详解

    spring2.5IOC控制反转详解 19. 五 / J2EE / 一条评论   基本的代码结构 1 IOC包下 基本的spring创建对象 将类添加到配置文件中,由容器创建. Source code ...

  6. Hibernate之通过hibernate.cfg.xml配置文件访问数据库的例子

    hibernate.cfg.xml文件内容: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ...

  7. 为编写网络爬虫程序安装Python3.5

    1. 下载Python3.5.1安装包1.1 进入python官网,点击menu->downloads,网址:https://www.python.org/downloads/ 1.2 根据系统 ...

  8. C语言基础10

    栈区间:在函数内部声明的变量都存放在栈区间,比如int char 数组 结构体 指针,只管申请,系统会自动帮我们回收,收回的时间是作用域结束之后,遵循的原则是"先进后出". int ...

  9. c++ ifstream ofstream 文件流

    #include <fstream>ofstream //文件写操作 内存写入存储设备 ifstream //文件读操作,存储设备读区到内存中fstream //读写操作,对打开的文件可进 ...

  10. EMMA: 免费java代码测试覆盖工具

    From:http://emma.sourceforge.net/ EMMA: a free Java code coverage tool   Code coverage for free: a b ...