【LeetCode】98. Validate Binary Search Tree 解题报告(Python & C++ & Java)
作者: 负雪明烛
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)的更多相关文章
- LeetCode: Validate Binary Search Tree 解题报告
Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST) ...
- [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 ...
- 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 ...
- 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 ...
- [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 ...
- [LeetCode] 98. Validate Binary Search Tree(是否是二叉搜索树) ☆☆☆
描述 解析 二叉搜索树,其实就是节点n的左孩子所在的树,每个节点都小于节点n. 节点n的右孩子所在的树,每个节点都大于节点n. 定义子树的最大最小值 比如:左孩子要小于父节点:左孩子n的右孩子要大于n ...
- 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)
[LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...
- 【LeetCode】99. Recover Binary Search Tree 解题报告(Python)
[LeetCode]99. Recover Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/p ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
随机推荐
- Golang使用validator进行数据校验及自定义翻译器
Golang使用validator进行数据校验及自定义翻译器 包下载:go get github.com/go-playground/validator/v10 一.概述 在接口开发经常会遇到一个问题 ...
- MariaDB——在Linux中查找数据库路径,并进入数据库
1.直接在命令行运营mysql,如果出现下图,说明数据库路径没有设置到环境变量里. 2.找出数据库路径,可以用ps -ef | grep my 命令,查找后台正在执行的命令任务中,包含my字母开头的所 ...
- 56-Remove Linked List Elements
Remove Linked List Elements My Submissions QuestionEditorial Solution Total Accepted: 61924 Total Su ...
- python写的多项式符号乘法
D:\>poly.py(x - 1) * (x^2 + x + 1) = x^3 - 1 1 import ply.lex as lex # pip install ply 2 import p ...
- Hive(十)【窗口函数】
目录 一.定义 窗口函数: 标准聚合函数 分析排名函数 二.语法 (1)窗口函数 over([partition by 字段] [order by 字段] [ 窗口语句]) (2)窗口语句 三.需求练 ...
- C++ 德才论
输入样例: 14 60 80 10000001 64 90 10000002 90 60 10000011 85 80 10000003 85 80 10000004 80 85 10000005 8 ...
- Stream collect Collectors 常用详细实例
返回List集合: toList() 用于将元素累积到List集合中.它将创建一个新List集合(不会更改当前集合). List<Integer> integers = Arrays.as ...
- 'this' pointer in C++
The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is avai ...
- canal安装与使用
安装 alpha的版本不是稳定的版本 wget https://github.com/alibaba/canal/releases/download/canal-1.1.4/canal.deploye ...
- apply 和 call 的区别
相同点: 都能够改变方法的执行上下文(执行环境),将一个对象的方法交给另一个对象来执行,并且是立即执行 不同点: call方法从第二个参数开始可以接收任意个参数,每个参数会映射到相应位置的func的参 ...