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. UIProgressView 圆角

    里面外面都变成圆角 不用图片 直接改变layer 重点是里面外面都是圆角哦 for (UIImageView * imageview in self.progress.subviews) { imag ...

  2. appStore应用发布流程

    原文转自: http://blog.sina.com.cn/s/blog_68661bd801019uzd.html       首先确定帐号是否能发布, https://developer.appl ...

  3. C#总结(3)

    这次我们来谈谈函数. C#的函数分为静态函数,和普通函数. 先上代码. using System; using System.Collections.Generic; using System.Lin ...

  4. [原]C++程序示例:涉及到抽象类、继承…

    C++复习题. 有助于理解: .h与.cpp分离 基类.派生类.抽象类 多态.纯虚函数 对象指针.引用 派生类使用基类的构造函数 ... =============================== ...

  5. 转:linux运维工程师

    运维中关键技术点解剖:1 大量高并发网站的设计方案:2 高可靠.高可伸缩性网络架构设计:3 网站安全问题,如何避免被黑?4 南北互联问题,动态CDN解决方案:5 海量数据存储架构 一.什么是大型网站运 ...

  6. T-SQL 创建、修改、删除数据库,表语法

    CREATE 语句 CREATE语句的开头都是一样的,然后是特定的细节. CREATE <object type> <object name> 一.CREATE DATABAS ...

  7. DataTable类

    DataTable是一个使用非常多的类,记得我在刚刚开始学习.Net的时候就已经了解并用过这个类,但如今再来看看,才发现这个类非常之复杂,复杂表现在哪些地方呢?主要是这个类与其他很多类都有关联,也就是 ...

  8. ##解决 ViewPager 调用 notifyDataSetChanged()无刷新:原理、解决办法##

    一.原理 转自:http://www.cnblogs.com/maoyu417/p/3740209.html 转载 http://www.67tgb.com/?p=624 最近项目结束,搞了一次代码分 ...

  9. HDU 5775 Bubble Sort(线段树)(2016 Multi-University Training Contest 4 1012)

    原址地址:http://ibupu.link/?id=31 Problem Description P is a permutation of the integers from 1 to N(ind ...

  10. ZOJ3574(归并排序求逆数对)

    Under Attack II Time Limit: 5 Seconds      Memory Limit: 65536 KB Because of the sucessfully calcula ...