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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree:  root = [6,2,8,0,4,7,9,null,null,3,5]

        _______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself
according to the LCA definition.

Note:

  • All of the nodes' values will be unique.
  • p and q are different and both values will exist in the BST.

求二叉搜索树(BST)的最近公共祖先(LCA)。最近公共祖先是指在一个树或者有向无环图中同时拥有v和w作为后代的最深的节点。

解法1:递归,

1. P, Q都比root小,则LCA在左树,我们继续在左树中寻找LCA

2. P, Q都比root大,则LCA在右树,我们继续在右树中寻找LCA

3. 其它情况,表示P,Q在root两边,或者二者其一是root,或者都是root,这些情况表示root就是LCA,直接返回root即可。

解法2: 迭代

判断标准同解法1,只是用迭代来实现。

Java:

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}

Java:

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//发现目标节点则通过返回值标记该子树发现了某个目标结点
if(root == null || root == p || root == q) return root;
//查看左子树中是否有目标结点,没有为null
TreeNode left = lowestCommonAncestor(root.left, p, q);
//查看右子树是否有目标节点,没有为null
TreeNode right = lowestCommonAncestor(root.right, p, q);
//都不为空,说明做右子树都有目标结点,则公共祖先就是本身
if(left!=null&&right!=null) return root;
//如果发现了目标节点,则继续向上标记为该目标节点
return left == null ? right : left;
}
}  

Python:

class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
s, b = sorted([p.val, q.val])
while not s <= root.val <= b:
# Keep searching since root is outside of [s, b].
root = root.left if s <= root.val else root.right
# s <= root.val <= b.
return root

C++:

class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root->val > max(p->val, q->val))
return lowestCommonAncestor(root->left, p, q);
else if (root->val < min(p->val, q->val))
return lowestCommonAncestor(root->right, p, q);
else return root;
}
};

C++:

class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (true) {
if (root->val > max(p->val, q->val)) root = root->left;
else if (root->val < min(p->val, q->val)) root = root->right;
else break;
}
return root;
}
};

  

 

类似题目:

[LeetCode] 236. Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先

 

All LeetCode Questions List 题目汇总 

[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先的更多相关文章

  1. 235 Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先

    给定一棵二叉搜索树, 找到该树中两个指定节点的最近公共祖先. 详见:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-s ...

  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 the BS ...

  3. [LeetCode] 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 ...

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

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

  6. 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 the BS ...

  7. (easy)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 the BS ...

  8. Java [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 ...

  9. Leetcode 235 Lowest Common Ancestor of a Binary Search Tree 二叉树

    给定一个二叉搜索树的两个节点,找出他们的最近公共祖先,如, _______6______ / \ ___2__ ___8__ / \ / \ 0 4 7 9 / \ 3 5 2和8的最近公共祖先是6, ...

随机推荐

  1. Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)-C. Magic Grid-构造

    Manthan, Codefest 19 (open for everyone, rated, Div. 1 + Div. 2)-C. Magic Grid-构造 [Problem Descripti ...

  2. Kotlin反射在属性上的应用实战

    继续研究Kotlin反射相关的东东,看代码: 接下来则遍历函数,来调一下,比如咱们先来调用一下带有2个参数的method方法,可以这样写: 其实在调用实例方法时的第一个参数永远都是要调用的那个实例,也 ...

  3. Python+Appium学习之启动手机APP或者浏览器

    一.启动浏览器:pycharm中python脚本如下: from appium import webdriver desired_caps ={ 'platformName':'Android', ' ...

  4. @Scope("prototype")

    spring中bean的scope属性,有如下5种类型: singleton 表示在spring容器中的单例,通过spring容器获得该bean时总是返回唯一的实例prototype表示每次获得bea ...

  5. springboot 整合Swagger2的使用

    Swagger2相较于传统Api文档的优点 手写Api文档的几个痛点: 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时. 接口返回结果不明确 不能直接在线测试接口,通常需要使用工 ...

  6. jmeter-多用户循环执行(存储token)

    1.从cvs文件中读取数据 登录接口读取文件: 2.读取token,保存token 在登录接口下添加 设置: 把token保存为全局变量: 设置: 输入${__setProperty(newtoken ...

  7. createTextRange 创建文本对象

    document.body.createTextRange 主要是用来对一些文本对象进行操作.比如你有一大段文字,都在同一个P标签内,但是你只希望通过JS改变其中的一小部分,这时就可以用createT ...

  8. 2019-2020-1 20199302《Linux内核原理与分析》第十一周作业

    缓冲区溢出 缓冲区溢出是指程序试图向缓冲区写入超出预分配固定长度数据的情况.这一漏洞可以被恶意用户利用来改变程序的流控制,甚至执行代码的任意片段.这一漏洞的出现是由于数据缓冲器和返回地址的暂时关闭,溢 ...

  9. chsh

    修改shell进程

  10. 推荐一款分布式微服务框架 Surging

    surging   surging 是一个分布式微服务框架,提供高性能RPC远程服务调用,采用Zookeeper.Consul作为surging服务的注册中心,集成了哈希,随机,轮询,压力最小优先作为 ...