【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree (2 solutions)
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.
解法一:不考虑BST的特性,对于一棵普通二叉树,寻找其中两个节点的LCA
深度遍历到节点p时,栈中的所有节点即为p的从根开始的祖先序列。
因此只需要比较p、q祖先序列中最后一个相同的祖先即可。
/**
* 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) {
// special cases
if(root == NULL)
return NULL;
if(p == root || q == root)
return root;
if(p == q)
return p; vector<TreeNode*> vp;
vector<TreeNode*> vq;
stack<TreeNode*> stk;
unordered_map<TreeNode*, bool> m; //visited
stk.push(root);
m[root] = true;
while(!stk.empty())
{
TreeNode* top = stk.top();
if(top->left && m[top->left] == false)
{
stk.push(top->left);
m[top->left] = true;
if(top->left == p)
{
vp = stkTovec(stk);
if(!vq.empty())
break;
}
if(top->left == q)
{
vq = stkTovec(stk);
if(!vp.empty())
break;
}
continue;
}
if(top->right && m[top->right] == false)
{
stk.push(top->right);
m[top->right] = true;
if(top->right == p)
{
vp = stkTovec(stk);
if(!vq.empty())
break;
}
if(top->right == q)
{
vq = stkTovec(stk);
if(!vp.empty())
break;
}
continue;
}
stk.pop();
}
int i = ;
for(; i < vp.size() && i < vq.size(); i ++)
{
if(vp[i] != vq[i])
break;
}
return vp[i-];
}
vector<TreeNode*> stkTovec(stack<TreeNode*> stk)
{
vector<TreeNode*> v;
while(!stk.empty())
{
TreeNode* top = stk.top();
stk.pop();
v.push_back(top);
}
reverse(v.begin(), v.end());
return v;
}
};

解法二:利用BST的性质,
p和q的LCA是恰好把p、q分叉的节点,也就是LCA的值介于p、q之间
从最高层的祖先root开始往下,
若不满足LCA条件,往p、q所在子树递归。
/**
* 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 - p->val) * (root->val - q->val) <= )
return root;
else if(root->val > p->val)
return lowestCommonAncestor(root->left, p, q);
else
return lowestCommonAncestor(root->right, p, q);
}
};

【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree (2 solutions)的更多相关文章
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...
- 【LeetCode】235. 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 th ...
- 【一天一道LeetCode】#235. Lowest Common Ancestor of a Binary Search Tree
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- 【easy】235. Lowest Common Ancestor of a Binary Search Tree
题意大概是,找两个节点的最低公共祖先 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNod ...
- LeetCode OJ 235. 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 BS ...
- 【leetcode❤python】235. Lowest Common Ancestor of a Binary Search Tree
#-*- coding: UTF-8 -*- # Definition for a binary tree node.# class TreeNode(object):# def __init ...
- 【LeetCode】236. Lowest Common Ancestor of a Binary Tree 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 236. Lowest Common Ancestor of a Binary Tree
https://www.cnblogs.com/grandyang/p/4641968.html http://www.cnblogs.com/grandyang/p/4640572.html 利用二 ...
- leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree
leetcode面试准备:Lowest Common Ancestor of a Binary Search Tree & Binary Tree 1 题目 Binary Search Tre ...
随机推荐
- sql-获取指定年份指定月份的天数
declare @年月 varchar(6) set @年月= '201803' --查询2015年2月有多少天 select day(dateadd(month,1,@年月+ '01 ')-1)
- 一个小框架,基于rx_retrofit2_mvp
离职在即,也没什么事情做,就鼓捣了一下.任意搭建了一个小框架,看看以后能不能搞出自己的一个model,好了.不说别的,上代码 1,先上依赖库 compile 'io.reactivex:rxandro ...
- Java 大型系统高并发大数据的处理方式
页面静态化 (页面层面的缓存) 缓存 (memcached.redis等,数据缓存.避免多次请求) 集群负载均衡(单机处理能力不足) 分库分表(大量数据的处理.原则分.分.分) 读写分离 队列.MQ. ...
- Virtualbox安装Ubuntu
每次安装虚拟机都是总要折腾一下,毕竟不是特别熟悉,几个小细节总要google半天,为了以后能愉快的玩耍.把这些问题都记录下来,免得再折腾. 此文档都来自其他人的文章,我保存在Evernote整理. 网 ...
- CSS外框高度自动适应
当有浮动float时,最外框会不跟随内容的高度而高: 解决办法一:清除浮动 clear:both <!DOCTYPE html> <html xmlns="http:// ...
- Invalid volume failure config value: 1
原因: hdfs-site.xml中的配置为: <property> <name>dfs.datanode.failed.volumes.tolerated</name& ...
- uni - 使用npm
一.使用 1. 在当前根目录初始化package.json npm init -y 2. 安装(自动生成node_modules文件夹) npm i packageName yarn add pack ...
- Plupload上传插件中文帮助文档
Plupload上传插件中文帮助文档 配置参数 实例化一个plupload对象时,也就是 new plupload.Uploader(),需要传入一个对象作为配置参数.后面内容中出现的plupload ...
- React (native) 相关知识
container component provider组件 react里的redux进阶玩法 react组件的生命周期 conductor / componentWillMount / render ...
- C# 只能输入字母或数字
c# 只能输入字母或者数字 或者退格符 方法一:KeyPress private void textBox2_KeyPress(object sender, KeyPressEventArgs e) ...