98. Validate Binary Search Tree

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 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.

1
2
3
4
5
6
7
8
9
10
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.

题目大意

校验是否是二叉搜索树。

校验规则:

左子树的所有节点值都比根节点小;

右子树的所有节点值都比根节点大;

左子树和右子树也是二叉搜索树

解题思路

DFS,根据题目所述的规则进行判定即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func isValidBST(_ root: TreeNode?) -> Bool {
guard let tree = root else { return true }
var ans = true
var rootVal = tree.val
func dfs(_ t: TreeNode, min: Int, max: Int) {
if let left = t.left {
//是否小于根节点,通过max判定左子树是否都小于根节点
if left.val >= t.val || left.val <= min || left.val >= max {
ans = false
return
}
dfs(left, min: min, max: t.val)
}
if let right = t.right {
//是否大于根节点,通过min判定右子树是否都大于根节点
if right.val <= t.val || right.val <= min || right.val >= max {
ans = false
return
}
dfs(right, min: t.val, max: max)
}
}
dfs(tree, min: Int.min, max: Int.max)
return ans
}
}
0%