Skip to content

Commit df389a5

Browse files
committed
树: 二叉搜索树
Change-Id: Iffc0850406ca16c8b06515e3b3b571baf2ec4b70
1 parent ef88754 commit df389a5

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* @lc app=leetcode.cn id=98 lang=golang
3+
*
4+
* [98] 验证二叉搜索树
5+
*
6+
* https://leetcode-cn.com/problems/validate-binary-search-tree/description/
7+
*
8+
* algorithms
9+
* Medium (27.53%)
10+
* Likes: 291
11+
* Dislikes: 0
12+
* Total Accepted: 40.8K
13+
* Total Submissions: 147.4K
14+
* Testcase Example: '[2,1,3]'
15+
*
16+
* 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
17+
*
18+
* 假设一个二叉搜索树具有如下特征:
19+
*
20+
*
21+
* 节点的左子树只包含小于当前节点的数。
22+
* 节点的右子树只包含大于当前节点的数。
23+
* 所有左子树和右子树自身必须也是二叉搜索树。
24+
*
25+
*
26+
* 示例 1:
27+
*
28+
* 输入:
29+
* ⁠ 2
30+
* ⁠ / \
31+
* ⁠ 1 3
32+
* 输出: true
33+
*
34+
*
35+
* 示例 2:
36+
*
37+
* 输入:
38+
* ⁠ 5
39+
* ⁠ / \
40+
* ⁠ 1 4
41+
* / \
42+
* 3 6
43+
* 输出: false
44+
* 解释: 输入为: [5,1,4,null,null,3,6]。
45+
* 根节点的值为 5 ,但是其右子节点值为 4 。
46+
*
47+
*
48+
*/
49+
50+
// @lc code=start
51+
/**
52+
* Definition for a binary tree node.
53+
* type TreeNode struct {
54+
* Val int
55+
* Left *TreeNode
56+
* Right *TreeNode
57+
* }
58+
*/
59+
func isValidBST(root *TreeNode) bool {
60+
var INT_MAX = int(^uint(0) >> 1)
61+
var INT_MIN = ^INT_MAX
62+
return helper(root, INT_MIN, INT_MAX)
63+
}
64+
65+
func helper(root *TreeNode, min int, max int) bool {
66+
if root == nil {
67+
return true
68+
}
69+
70+
if root.Val >= max || root.Val <= min {
71+
return false
72+
}
73+
return helper(root.Left, min, root.Val) && helper(root.Right, root.Val, max)
74+
}
75+
// @lc code=end
76+

0 commit comments

Comments
 (0)