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 ...
随机推荐
-
【BZOJ】4056: [Ctsc2015]shallot
题意 在线.可持久化地维护一条二维平面上的折线,支持查询与任意一条直线的交点个数. 点的个数和操作个数小于\(10^5\) 分析 一条折线可以用一个序列表示,可持久化序列考虑用可持久化treap. 如 ...
-
elasticsearch scroll api--jestclient invoke
@Test public void testScroll(){ JestClientFactory factory = new JestClientFactory(); factory.setHttp ...
-
MySQL临时表
当你创建临时表的时候,你可以使用temporary关键字.如: create temporary table tmp_table(name varchar(10) not null,passwd ch ...
-
如何排版 微信公众号「代码块」之 MarkEditor
前段时间写过一篇文章 如何排版微信公众号「代码块」,讲的是如何使用浏览器插件 Markdown Here 来排版代码块.虽然用 Markdown Here 排版出来的样式还不错,但存在一个问题,就是代 ...
-
ajax分页借鉴
大家好这是我分页是用的代码希望大家可以相互交流ajax局部刷新 var pageindex = 1; var where = ""; var Pname = "" ...
-
初学Python—列表和元组
一.什么是列表 列表是一系列数据的集合 二.列表的引用 首先定义一个列表 names=["alex","bob","alice"," ...
- svn各种表示含义及解决
-
XSS-HTML&;javaSkcript&;CSS&;jQuery&;ajax
1.设置不同的样式列表 <style> ul.a{list-style-tyrp:circle;} ul.b{list-style-type:square;} ul.c{list ...
-
利用bat批处理做启动mongodb脚本
文章开始,我们先回顾一下,如何用cmd命令窗口开启mongodb数据库,命令如下: 开启mongodb数据库 cd D:\Program Files\MongoDB\bin mongod --depa ...
-
Tomcat:Several ports are already in use问题
Several ports (8005, 8080, 8009) required by Tomcat v6.0 Server at localhost are already in use. The ...