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. 【应用】R--判断类别型属性之间是否有相关性(相互之间是否独立)

    检验某学区所有在售房源中,小区与楼栋类别(低层:多层;小高层:高层)是否相关 导入数据: > house<- read.table("house_data.txt", ...

  2. Flask莫名其妙特别慢

    其他上网都正常,代理服务器.防火墙反复检查都没问题,最后,严重怀疑腾讯的mysql服务器,监控是这样的: 突然下降那段就很不正常. 后面忽然就崩溃了,死活都连不上.把可疑连接都关闭了,把防火墙都关闭了 ...

  3. sql存储过程加密和解密(MSSQL)

    在网络上,看到有SQL Server 2000和SQL Server 2005 的存储过程加密和解密的方法,后来分析了其中的代码,发现它们的原理都是一样的.后来自己根据实际的应用环境,编写了两个存储过 ...

  4. 大量带BPM的跑步歌曲/跑步音乐下载

    20150110停止更新告知:不知不觉本帖更新有近半年了.从最开始跑步已经四年多,一直是听着音乐跑的,音乐支持.陪伴.丰富着我的跑步之旅.直到上个月因一次觉得音乐吵,我开始有意地摘掉耳机去跑步,并开始 ...

  5. oracle 复制表结构表数据

    create table Uc_t_Department3 as (select * from Uc_t_Department where 1=2);insert into Uc_t_Departme ...

  6. c数据库读写分离和负载均衡策略

    最近在学习数据库的读写分离和主从复制,采用的是一主多从策略,采用轮询的方式,读取从数据库的内容.但是,假如某一台从数据库宕机了,而客户端不知道,每次轮选到此从数据库,不都要报错?到网上查阅了资料,找到 ...

  7. JavaWeb之tomcat安装、配置与使用(一)

    一.Tomcat下载与安装: 1.直接到官网下载Tomcat安装程序包:http://tomcat.apache.org/ 2.下载下来后是个压缩包,如:apache-tomcat-7.0.40.zi ...

  8. 手把手教你从零实现Linux misc设备驱动一(基于友善之臂4412开发板)

    关于怎样来写一个misc设备,在前面有篇文章已经介绍了大致的流程,如今就让我们来实现一个最简单的misc设备驱动. http://blog.csdn.net/morixinguan/article/d ...

  9. Python学习笔记_01:基本概念介绍

    目录 1.Python语言简介 2.Python中常用数据结构 2.1什么是列表? 2.2什么是元组? 2.3什么是字典? 2.4索引及分片 3.其它基本概念 3.1数据类型和变量 3.2生成器 3. ...

  10. infobright系列二:数据迁移

    安装之后把之前infobright的数据迁移到新安装的infobright上. 1:挺掉相关的服务 2:scp 把旧数据拷到新安装的infobright上 3:修改/etc/my-ib.cnf的数据目 ...