作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

Total Accepted: 67533 Total Submissions: 178900 Difficulty: Easy

题目描述

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:

  1. All of the nodes’ values will be unique.
  2. p and q are different and both values will exist in the BST.

题目大意

在一个BST中,查找p和q节点的最小公共祖先。

解题方法

注意是BST,那么使用分而治之的策略,用递归来找到左边和右边的最低的公共祖先。

答案:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||p==root||q==root){
return root;
}
//devide
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q); //conquer
if(left!=null&&right!=null){
return root;
}else if(left!=null){
return left;
}else{
return right;
}
}
}

AC:11ms


二刷,python

第一遍做这个题是两年前,现在用Python刷这个感觉特别简单。

因为BST本身的属性,所以比较节点的值和根节点的值的大小就知道下一步去哪里查找了。很简单,看代码。

递归版本:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if min(p.val, q.val) <= root.val and max(p.val, q.val) >= root.val:
return root
elif p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
elif p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)

循环版本:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
break
return root

这个题是236. Lowest Common Ancestor of a Binary Tree的特例,所以可以直接使用236的代码就能通过。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right

日期

2016/5/1 14:05:25
2018 年 6 月 22 日 ———— 这周的糟心事终于完了
2018 年 11 月 19 日 —— 周一又开始了

【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)的更多相关文章

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

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

  4. LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告

    https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest ...

  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. 【机器学习与R语言】8- 神经网络

    目录 1.理解神经网络 1)基本概念 2)激活函数 3)网络拓扑 4)训练算法 2.神经网络应用示例 1)收集数据 2)探索和准备数据 3)训练数据 4)评估模型 5)提高性能 1.理解神经网络 1) ...

  2. 数仓day03-----日志预处理

    1. 为什么要构建一个地理位置维表(字典) 在埋点日志中,有用户的地理位置信息,但是原始数据形式是GPS坐标,而GPS坐标在后续(地理位置维度分析)的分析中不好使用.gps坐标的匹配,不应该做这种精确 ...

  3. 【Git项目管理】Git分支 - 远程分支

    远程分支 远程引用是对远程仓库的引用(指针),包括分支.标签等等. 你可以通过 git ls-remote (remote) 来显式地获得远程引用的完整列表,或者通过 git remote show ...

  4. Linux环境下为普通用户添加sudo权限

    系统环境:Centos6.5 1.背景: sudo是Linux系统管理指令,是允许系统管理员让普通用户执行一些或者全部root命令的一个工具.Linux系统下,为了安全,一般来说我们操作都是在普通用户 ...

  5. Linux学习 - 压缩解压命令

    一." .gz "压缩文件 1 压缩语法 gzip  [文件] 2 解压语法 gunzip  [压缩文件] 3 注 gzip只能压缩文件 gzip不保留原文件 二." . ...

  6. dbeaver可视化工具-连接clickhouse

    下载地址 https://dbeaver.io/download/ 本次下载的是ZIP包,这种方式方便移动/备份软件 此软件可连接多种数据库,这里是连接clickhouse 新建连接 点击 上面的倒三 ...

  7. OSGI 理论知识

    下面列出了主要的控制台命令: 表 1. Equinox OSGi 主要的控制台命令表 类别 命令 含义 控制框架 launch 启动框架 shutdown 停止框架 close 关闭.退出框架 exi ...

  8. mybatis处理集合、数组参数使用in查询等语句的两种方法

    对于mybatis的参数类型是集合数组的时候进行查询. 第一种:参数list使用mybatis的标签 SELECT * FROM TABLE_NAME AS a <where> <i ...

  9. 关于for与forEach遍历集合中对集合进行操作的问题

    遍历List集合,在循环中再对List集合进行操作,有时候会遇到ConcurrentModificationException(并发修改异常);其实只有在forEach循环集合再对集合操作会发生异常: ...

  10. [BUUCTF]PWN14——not_the_same_3dsctf_2016

    [BUUCTF]PWN14--not_the_same_3dsctf_2016 题目网址:https://buuoj.cn/challenges#not_the_same_3dsctf_2016 步骤 ...