【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 ...
随机推荐
- Android -- Drag&&Drop
Android3.0提供了drag/drop框架,利用此框架可以实现使用拖放手势将一个view拖放到当前布局中的另外一个view中. 实现拖放的步骤 首先,我们先了解一下拖放过程,从官方文档可以知道, ...
- NLP 中的embedding layer
https://blog.csdn.net/chuchus/article/details/78386059 词汇是语料库的基本元素, 所以, 使用embedding layer来学习词嵌入, 将一个 ...
- BiLSTM-CRF模型中CRF层的解读
转自: https://createmomo.github.io/ BiLSTM-CRF模型中CRF层的解读: 文章链接: 标题:CRF Layer on the Top of BiLSTM - 1 ...
- Android Fragment的使用(转载)
可以分为下面的几部分: 使用支持库 创建一个Fragment 创建一个动态UI 多个Fragment之间的通信 1.使用支持库 如果您的应用需要运行在3.0及以上的版本,可以忽略这部分内容. 如果您的 ...
- Mockito单测,mock service层的mapper
转载:https://blog.csdn.net/paincupid/article/details/53561435 1.引入mockito jar包 <dependency> < ...
- 【转】Java抽象类与接口的区别
很多常见的面试题都会出诸如抽象类和接口有什么区别,什么情况下会使用抽象类和什么情况你会使用接口这样的问题.本文我们将仔细讨论这些话题. 在讨论它们之间的不同点之前,我们先看看抽象类.接口各自的特性. ...
- 编程之美 1.1 让cpu占用率曲线听你指挥(多核处理器)
[目录] 不考虑其他进程,cpu画正弦曲线 获取总体cpu利用率 获取多核处理器单个cpu利用率 考虑其他进程,cpu画正弦曲线 下面的程序针对多核处理器,可以设置让任何一个cpu显示相应的曲线(本文 ...
- Linux中使用ps、awk、sh一起批量杀死所有的dotnet进程。
一.操作 Linux中使用ps.awk.sh一起批量杀死所有的dotnet进程. 二.参考命令 ps -ef|grep dotnet|awk 'NR==2{print "kill " ...
- Sqlite执行insert or ignore 或insert or replace语句。
Sqlite执行insert or ignore 或insert or replace语句. ,); ,); 上面的第一条语句是每次执行时,如果不存在,则添加,如果存在,则更新. 上面的第二条语句是每 ...
- 动态加载jar包(一)
一.编写被调用的类 package com.qunar.helloworld; public class HelloWorld { public String sayHello(){ return ( ...