Lowest Common Ancestor of a Binary Search Tree、Lowest Common Ancestor of a Binary Search Tree

时间:2022-12-23 15:15:19

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&period; Convert Sorted Array to Binary Search Tree 、109&period; Convert Sorted List to Binary Search Tree

    108. Convert Sorted Array to Binary Search Tree 这个题使用二分查找,主要要注意边界条件. 如果left > right,就返回NULL.每次更新的 ...

  2. 36&period; Construct Binary Tree from Inorder and Postorder Traversal &amp&semi;&amp&semi; 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. 主席树&lbrack;可持久化线段树&rsqb;&lpar;hdu 2665 Kth number、SP 10628 Count on a tree、ZOJ 2112 Dynamic Rankings、codeforces 813E Army Creation、codeforces960F&colon;Pathwalks &rpar;

    在今天三黑(恶意评分刷上去的那种)两紫的智推中,突然出现了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. 决策树&lpar;中&rpar;-集成学习、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、伪&period;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. Jquery入门之---------基本事件------------

    Javascript有一个非常重要的功能,就是事件驱动. 当页面完成加载后,用户通过鼠标或键盘触发页面中绑定事件的元素即可触发.Jquery为开发者更有效率的编写事件行为,封装了大量有益的事件方法供我 ...

  2. Strongly connected

    hdu4635:http://acm.hdu.edu.cn/showproblem.php?pid=4635 题意:给你一个有向图,然后问你最多可以加多少条边,是的原图不是一个强连通图. 题解:这一题 ...

  3. 详解一下网络广告cpc、cpm、cpl、cpa、cps、cpr的计费方法是什么

    CPC(Cost per click)按照 广告 点击数 计费 ,限定一个IP在24小时内只能点击一次.CPM(Cost per mille)按照广告显示次数来计算广告费,可在短时间内为 网站 带来巨 ...

  4. 关于C&plus;&plus;11右值引用和移动语义的探究

    关于C++11右值引用和移动语义的探究

  5. MemoryStream生成Excel

    public static MemoryStream ToExcel<T>(List<T> list, string filePath = null) { var memory ...

  6. C&num; 添加动态属性

    1.ExpandoObject(System.Dynamic) 2.JObject(Newtonsoft.Json.Linq)

  7. Unity ---WidgetsUI CreateTileView Demo

    以下教程基于:WidgetsUI 第三方扩展包 WidgtsUI 官网文档地址:https://ilih.ru/unity-assets/UIWidgets/docs/ 1.创建一个空GameObje ...

  8. libuv源码分析

    项目开发过程中经常使用了基于libuv库封装的库接口来实现异步处理,一直没仔细研究过这些接口的内部如何实现,因此也就没有掌握它的设计思想.今天花了点时间研究了其事件循环内部的一些过程,总算有了一些理解 ...

  9. js的等于号&equals;&equals;的判断

    var str=0; str == "" 将返回true:

  10. 知问前端——Ajax提交表单

    本文,运用两大表单插件,完成数据表新增的工作. 一.创建数据库 创建一个数据库,名称为:zhiwen,表——user表,字段依次为:id.name.pass.email.sex.birthday.da ...