作者: 负雪明烛
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. Metabolomics Workfolw

    推荐R语言界的国内大佬于淼写的代谢组学workflow,包含了大部分代谢组学(以及暴露组)的数据分析方法. Meta-Workflow 主要内容包括: Sample collection Pretre ...

  2. 数据分析体系 — 用户粘性的两个计算指标(DAU/MAU和月人均活跃天数)

    很多运营都了解DAU(日活跃用户数)和MAU(月活跃用户数)的重要性,但在某些情况下这两个数值本身并不能反映出太多问题,这个时候就要引用到[DAU/MAU]的概念,即[日活/月活] 用户粘性的两个计算 ...

  3. Linux之文件读取查看之cat、head、tail、tac、rev、more、less

    Linux文件查看的命令有很多,如cat.head.tail.tac.rev.more.less等 1. cat之查看文件内容 NAME cat - 连接文件并在标准输出上打印(concatenate ...

  4. C++面试基础篇(二)

    1.数组与指针的区别 数组下标运算实际上都是通过指针进行的. 数组名代表着指向该数组中下标为0的元素的指针,但有例外:sizeof(数组名)返回整个数组的大小,而非指针大小:&数组名返回一个指 ...

  5. 答应我,这次必须搞懂!痛点难点Promise。(小点心async/await,基于Promise的更优方案)

    Promise 出现的原因 在 Promise 出现以前,我们处理一个异步网络请求,大概是这样: // 请求 代表 一个异步网络调用. // 请求结果 代表网络请求的响应. 请求1(function( ...

  6. Templates and Default Arguments

    Default parameters for templates in C++: Like function default arguments, templates can also have de ...

  7. spring注解-扩展原理

    AnnotationConfigApplicationContext(IOC容器)的有参构造方法中,在refresh()里对这些组件进行初始化 BeanPostProcessor bean后置处理器, ...

  8. Linux系统信息查看命令(ZZ)

    http://hi.baidu.com/thinkdifferent/blog/item/22f4a80161630e011d958384.html转自一个baidu师兄的博客,很好的一个总结,推荐下 ...

  9. jQuery - 的几种删除方法,还有他们的区别

    1.empty() 清空节点,它能清空元素中的所有后代节点,不能删除自己本身这个节点 2.remove() 该节点与该节点所包含的所有后代节点将同时被删除,提供传递一个筛选的表达式,删除指定合集中的元 ...

  10. 使用beanFactory工厂实例化容器的方式实现单例模式

    //配置文件bean.properties(注意书写顺序) accountService=com.itheima.service.impl.AccountServiceImplaccountDao=c ...