作者: 负雪明烛
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】write.table输出数据带有行名?

    目录 问题 解决一 解决二 问题 这个问题应该很常见吧.R中输出数据框时,想要把行名和列名都输出.如果直接输出的话,输出的结果列名会往前移动一位,这显然不是我们想要的. 直接上例子: > a = ...

  2. 【基因组注释】同源注释比对软件tblastn、gamp和exonerate比较

    基因结构预测中同源注释策略,将mRNA.cDNA.蛋白.EST等序列比对到组装的基因组中,在文章中通常使用以下比对软件: tblastn gamp exonerate blat 根据我的实测,以上软件 ...

  3. R数据科学-3

    R数据科学(R for Data Science) Part 3:编程 转换--可视化--模型 --------------第13章 使用magrittr进行管道操作----------------- ...

  4. header 301,显示302

    header 301,显示302 一定要注意Location 后面的":"前后都不能有空格 header('HTTP/1.1 301 Moved Permanently'); he ...

  5. gg=G

    1.代码格式化对齐 2.直接按下ESE模式下就可以来执行了

  6. 每日自动健康打卡(Python+腾讯云服务器)

    每日自动健康打卡(Python+腾讯云服务器) 1.配置需要 python3.7,Chrome或者Edeg浏览器,Chrome驱动或者Edge驱动 #需要配置selenium库,baidu-aip库, ...

  7. 01 Windows安装C语言环境

    安装C语言运行环境 双击打开安装文件,进行安装 配置环境变量 将: C:\MinGW\bin;添加到Path变量里面. 验证环境变量是否成功 gcc –v 出现如下图所示,证明安装成功

  8. cephfs文件系统场景

    创建cephfs文件系统: [cephfsd@ceph-admin ceph]$ cd /etc/ceph [cephfsd@ceph-admin ceph]$ ceph fs ls No files ...

  9. 【leetcode】85. Maximal Rectangle(单调栈)

    Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing onl ...

  10. 【Spring Framework】spring管理自己new的对象

    使用AutowireCapableBeanFactory手动注入 使用.newInstance();创建对象的话,如果其他对象都使用Spring Autowired,还需要手动创建所有依赖的Bean: ...