leetCode-0098_验证二叉搜索树


题目描述

英文题目

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:

1
2
3
4
5
Input:
2
/ \
1 3
Output: true

Example 2:

1
2
3
4
5
6
7
8
    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.
中文题目

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

1
2
3
4
5
输入:
2
/ \
1 3
输出: true

示例 2:

1
2
3
4
5
6
7
8
9
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。

解决方法

方法一
  • 描述

初始化时带入系统最大值和最小值,在递归过程中换成它们自己的节点值,用long代替int就是为了包括int的边界条件

  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool isValid_BST(struct TreeNode *root, long min, long max)
{
if (!root) {
return true;
}

if (root->val <= min || root->val >= max) {
return false;
}

return isValid_BST(root->left, min, root->val) && isValid_BST(root->right, root->val, max);
}

bool isValidBST(struct TreeNode* root) {
return isValid_BST(root, LONG_MIN, LONG_MAX);
}
方法二
  • 描述

用递归的中序遍历,但不同之处是不将遍历结果存入一个数组遍历完成再比较,而是每当遍历到一个新节点时和其上一个节点比较,如果不大于上一个节点那么则返回false,全部遍历完成后返回true

  • 源码
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
struct TreeNode *pre;
void inOrder(struct TreeNode *root, int *res)
{
if (!root) {
return;
}

inOrder(root->left, res);
if (!pre) {
pre = root;
}
else {
if (root->val <= pre->val) {
*res = 0;
}
pre = root;
}
inOrder(root->right, res);
}

bool isValidBST(struct TreeNode* root) {
int res = 1;
pre = NULL;
inOrder(root, &res);
if (res == 1) {
return true;
}
return false;
}

题目来源

Validate Binary Search Tree

验证二叉搜索树