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)的更多相关文章

  1. 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...

  2. 【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 ...

  3. 【一天一道LeetCode】#235. Lowest Common Ancestor of a Binary Search Tree

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

  4. 【easy】235. Lowest Common Ancestor of a Binary Search Tree

    题意大概是,找两个节点的最低公共祖先 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNod ...

  5. 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 ...

  6. 【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 ...

  7. 【LeetCode】236. Lowest Common Ancestor of a Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  8. 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 利用二 ...

  9. 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 ...

随机推荐

  1. 使用 CSS 接收用户的点击事情并对相关节点进行操作

    问题背景:使用纯 CSS 方案,实现导航栏tab切换 实现 Tab 切换的难点在于如何使用 CSS 接收到用户的点击事情并对相关的节点进行操作.即是: 如何接收点击事件 如何操作相关DOM 下面看看如 ...

  2. Spark的动态资源分配

    跑spark程序的时候,公司服务器需要排队等资源,参考一些设置,之前不知道,跑的很慢,懂得设置之后简直直接起飞. 简单粗暴上设置代码: def conf(self): conf = super(Tbt ...

  3. Win10系统80端口被系统进程占用

    一.问题 有系统需要用到80端口,为了方便,但是发现80端口被占用,执行netstat -ano 发现80端口竟然被一个System process占用了,当然这个是不能被杀掉的 二.解决问题 在网上 ...

  4. 教育单元测试mock框架优化之路(下)

    转载:https://sq.163yun.com/blog/article/169563599967031296 四.循环依赖的解决 果然! 当我将@SpyBean应用到存在有循环依赖的Bean上时, ...

  5. 分享几套生成iMac相关高逼格免费mockup的素材和在线工具

    好久没有过来转, 今天姐姐我分享几套高逼格的iMac相关设计资源, 希望各位靓妹帅哥会喜欢, 最重要滴是,都是FREE,此处应有掌声~~~ , yeah!! iMac桌面效果Mockup 只需要下载后 ...

  6. MSSQL 2005/2008 日志压缩清理方法小结

    适用于SQL Server 2005的方法 --------------------------------------------- 复制代码 代码如下: USE DNName GO 1,清理日志 ...

  7. 使用PyInstaller打包Python角本为exe程序

    一.经过测试 在Windows平台请使用Windows平台的pyinstaller,Linux平台请使用Linux平台的Pyinstall角本. 二.命令如下: pyinstaller -F --ic ...

  8. springboot整合mybatis的两种方式

    https://blog.csdn.net/qq_32719003/article/details/72123917 springboot通过java bean集成通用mapper的两种方式 前言:公 ...

  9. J2EE用监听器实现同一用户只能有一个在线

    这里我们讨论的是已登陆或将要登陆的用户,游客不在讨论的范围之内.这一点大家应该很容易就能理解的吧.                那么我们应该怎样去实现同一用户只能有一个在线这样的一个小功能呢? 有人 ...

  10. sql语句 case

    case: SELECT stdname, max( CASE WHEN stdsubject = '语文' THEN result ELSE 0 END) "语文", max( ...