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


题目地址:https://leetcode.com/problems/validate-binary-search-tree/#/description

题目描述

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input:
2
/ \
1 3
Output: true

Example 2:

    5
/ \
1 4
/ \
3 6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
is 5 but its right child's value is 4.

题目大意

判断一棵树是不是BST。

解题方法

递归

很显然,二叉树的题目可以使用递归进行解决。

根据BST的定义,左子树的值要在(min,mid)之间,右子树的值在(mid,max)之间,这个mid值并不是中位数而是当前节点的值。

定义一个辅助函数,要给这个辅助函数传入当前要判断的节点,当前要判断的这个节点的取值下限和取值上限。然后使用递归即可,每次要计算下一个节点的时候都要根据这个节点是左孩子还是右孩子对其取值的区间进行更新。

# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.valid(root, float('-inf'), float('inf')) def valid(self, root, min, max):
if not root: return True
if root.val >= max or root.val <= min:
return False
return self.valid(root.left, min, root.val) and self.valid(root.right, root.val, max)

C++代码如下:

/**
* 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:
bool isValidBST(TreeNode* root) {
if (!root)
return true;
return helper(root, LONG_MIN, LONG_MAX);
} bool helper(TreeNode* root, long minVal, long MaxVal) {
if (!root)
return true;
if (root->val >= MaxVal || root->val <= minVal)
return false;
return helper(root->left, minVal, root->val) && helper(root->right, root->val, MaxVal);
}
};

Java代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValid(TreeNode root, long min, long max){
if(root == null){
return true;
}
long mid = root.val;
if(mid <= min || mid >= max){
return false;
}
return isValid(root.left, min, mid) && isValid(root.right, mid, max);
}
}

BST的中序遍历是有序的

众所周知,BST最重要的性质就是:BST的中序遍历是有序的。所以这个题能不能通过这个性质来解决呢?答案是肯定的。

也就是说,已知一个二叉树的中序遍历是有序的,能判断这个二叉树是BST吗?加上一个条件就可以,这个条件就是该中序遍历不能包含重复元素。

准确的证明我没想好,不过我们可以想象一下,中序遍历不就是左孩子-根节点-右孩子的这个顺序遍历么,如果每个子树都满足左孩子<根节点<右孩子,那就应该是个BST吧。

python代码如下:

# 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 isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
res = []
self.inOrder(root, res)
return res == sorted(res) and len(res) == len(set(res)) def inOrder(self, root, res):
if not root: return []
l = self.inOrder(root.left, res)
if l:
res.extend(l)
res.append(root.val)
r = self.inOrder(root.right, res)
if r:
res.extend()

下面是C++对这个题的解法,并没有使用上面python的做法,而是用一个变量维护前面遍历到的节点,在BST的中序遍历中,每个位置的元素都应该大于前面遍历到的节点。代码如下:

/**
* 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:
bool isValidBST(TreeNode* root) {
prev_ = nullptr;
return inOrder(root);
}
private:
TreeNode* prev_;
bool inOrder(TreeNode* root) {
if (!root) return true;
if (!inOrder(root->left)) return false;
if (prev_ && root->val <= prev_->val) return false;
prev_ = root;
return inOrder(root->right);
}
};

参考资料:http://zxi.mytechroad.com/blog/tree/leetcode-98-validate-binary-search-tree/

日期

2017 年 4 月 17 日
2018 年 3 月 23 日 —— 科目一考了100分哈哈哈哈~嗝~
2019 年 1 月 19 日 —— 有好几天没有更新文章了

【LeetCode】98. Validate Binary Search Tree 解题报告(Python & C++ & Java)的更多相关文章

  1. LeetCode: Validate Binary Search Tree 解题报告

    Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST) ...

  2. [LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  3. Leetcode 98. Validate Binary Search Tree

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  4. leetcode 98 Validate Binary Search Tree ----- java

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  5. [leetcode]98. Validate Binary Search Tree验证二叉搜索树

    Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as ...

  6. [LeetCode] 98. Validate Binary Search Tree(是否是二叉搜索树) ☆☆☆

    描述 解析 二叉搜索树,其实就是节点n的左孩子所在的树,每个节点都小于节点n. 节点n的右孩子所在的树,每个节点都大于节点n. 定义子树的最大最小值 比如:左孩子要小于父节点:左孩子n的右孩子要大于n ...

  7. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  8. 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)

    [LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

随机推荐

  1. python故障

    问题: ImportError: No module named dns.resolver 解决: 通过包管理工具pip安装dnspython pip install dnspython

  2. Linux生产应用常见习题汇总

    1.如果想修改开机内核参数,应该修改哪个文件? C A./dev/sda1 (scsi sata sas,是第1块盘的第1个分区) B./etc/fstab (开机磁盘自动挂载配置文件) C./etc ...

  3. lua_newthread的真正意义

    lua_newthread 这个接口,存在误导性,很多人第一次试图用它来解决多线程问题时,都会入坑. 实际上,这个接口真正的用法,是给那些在lua更底层的某些行为(通常是递归)导致了lua的栈溢出而准 ...

  4. MapReduce02 序列化

    目录 MapReduce 序列化 概述 自定义序列化 常用数据序列化类型 int与IntWritable转化 Text与String 序列化读写方法 自定义bean对象实现序列化接口(Writable ...

  5. 看动画学算法之:二叉搜索树BST

    目录 简介 BST的基本性质 BST的构建 BST的搜索 BST的插入 BST的删除 简介 树是类似于链表的数据结构,和链表的线性结构不同的是,树是具有层次结构的非线性的数据结构. 树是由很多个节点组 ...

  6. Kafka 集群安装部署

    2.1 安装部署 2.1.1 集群规划 192.168.1.102 192.168.1.103 192.168.1.104 zookeeper zookeeper zookeeper kafka ka ...

  7. 【Android】我有放入Icon到mipmap,但不显示,只显示安卓机器人Icon(Android 8.0 图标适配)

    首先,放上别人写的博客,而我自己的博客,只会写大概思路,给自己留给备忘 https://blog.csdn.net/guolin_blog/article/details/79417483 其实会发生 ...

  8. C++ 成绩排名

    1004 成绩排名 (20分)   读入 n(>)名学生的姓名.学号.成绩,分别输出成绩最高和成绩最低学生的姓名和学号. 输入格式: 每个测试输入包含 1 个测试用例,格式为 第 1 行:正整数 ...

  9. 二叉树——Java实现

    1 package struct; 2 3 interface Tree{ 4 //插入元素 5 void insert(int value); 6 //中序遍历 7 void inOrder(); ...

  10. JavaIO——System对IO的支持、序列化

    1.系统类对IO的支持 在我们学习PriteWriter.PrintStream里面的方法print.println的时候是否观察到其与我们之前一直使用的系统输出很相似呢?其实我们使用的系统输出就是采 ...