作者: 负雪明烛
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. 在windows下使用shell,运行shell脚本

    在Windows操作系统下运行Shell脚本,缺少的只是一个Git软件.其下载路径为Git - Downloading Package. 安装之后,将安装路径下的bin文件夹的路径作为环境变量.于是我 ...

  2. Java 读取txt文件生成Word文档

    本文将以Java程序代码为例介绍如何读取txt文件中的内容,生成Word文档.在编辑代码前,可参考如下代码环境进行配置: IntelliJ IDEA Free Spire.Doc for Java T ...

  3. 利用抖音Cookie充值接口提取支付链接,个人调起原生微信h5支付宝h5支付

    最近开始搞一些个人支付通道的开发,方便个人不用和第三方平台签约就能收款,省去很多流程手续的成本. 然后翻了一下网上并没有太多现成的技术教程,只能自己研究着搞了. 这次要分享的是利用抖音的充值接口,去分 ...

  4. 巩固javaweb的第十九天

    巩固内容: 使用 form 元素 使用 form 元素封装要提交的信息 要向服务器提交信息,需要使用 form 元素,所有要提交的信息都应该在 form 内部.在 注册界面中,所有要输入的信息都位于 ...

  5. Yarn 生产环境核心配置参数

    目录 Yarn 生产环境核心配置参数 ResourceManager NodeManager Container Yarn 生产环境核心配置参数 ResourceManager 配置调度器 yarn. ...

  6. KMP算法中的next函数

    原文链接:http://blog.csdn.net/joylnwang/article/details/6778316/ 其实后面大段的代码都可以不看 KMP的关键是next的产生 这里使用了中间变量 ...

  7. 双向链表——Java实现

    双向链表 链表是是一种重要的数据结构,有单链表和双向链表之分:本文我将重点阐述不带头结点的双向链表: 不带头结点的带链表 我将对双链表的增加和删除元素操作进行如下解析 1.增加元素(采用尾插法) (1 ...

  8. 技术预演blog

    canal整合springboot实现mysql数据实时同步到redis spring+mysql集成canal springboot整合canal监控mysql数据库 SpringBoot cana ...

  9. AFNetworking 网络错误提示data转换字符串

    AFN在进行网络交互时,有时候会碰到返回502.500.404的时候.后台的总需要你配合他查出问题所在.但是AFN在返回数据序列化时解析错误只会转成NSData类型的数据,如果直接扔给后台Data的数 ...

  10. Activiti工作流引擎使用详解(一)

    一.IDEA安装activiti插件 在插件库中查找actiBPM,安装该插件,如果找不到该插件,请到插件库中下载该包手动安装,插件地址 http://plugins.jetbrains.com/pl ...