LeetCode: 98. Validate Binary Search Tree
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 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:
2
/ \ 1 3
Binary tree [2,1,3]
, return true
.
Example 2:
1
/ \ 2 3
Binary tree [1,2,3]
, return false
.
题目大意: 判断给定二叉树是否是 BST(二叉搜索树)。
解题思路
- 方法一: 由于 BST 的中序遍历是递增序列, 因此只需要中序列遍历,判断是否满足要求即可。
- 方法二: 递归地判断相关子树是否在给定的区间内(左子树的元素都大于根节点的元素,右节点的元素都小于根节点的元素)。
AC 代码
- 方法一:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
// 由于 BST 的中序遍历是递增序列, 因此只需要中序列遍历,判断是否满足要求即可
class Solution {
private:
// 中序遍历
void inOrderScan(TreeNode* root, vector<int>& inOrderSequence)
{
if(root == nullptr) return;
// 中序遍历左子树
inOrderScan(root->left, inOrderSequence);
// 读取根节点
inOrderSequence.push_back(root->val);
// 中序遍历右子树
inOrderScan(root->right, inOrderSequence);
}
// 判断给定序列的 [beg, end) 区间是否是递增序列
bool isAscendSequence(const vector<int>& inOrderSequence, int beg, int end)
{
if(beg+1 >= end) return true;
else if(inOrderSequence[beg] < inOrderSequence[beg+1]) return isAscendSequence(inOrderSequence, beg+1, end);
else return false;
}
public:
bool isValidBST(TreeNode* root) {
// root 的中序遍历序列
vector<int> inOrderSequence;
inOrderScan(root, inOrderSequence);
return isAscendSequence(inOrderSequence, 0, inOrderSequence.size());
}
};
- 方法二:
/** * 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 {
private:
// 判断给定子树的元素是否在区间 (min, max) 中
bool isValidBSTRef(TreeNode* root, long long min = LLONG_MIN, long long max = LLONG_MAX) {
bool bRet = false;
do
{
if(root == nullptr)
{
bRet = true;
break;
}
if(root->val <= min || root->val >= max) break;
// 左子树的元素应该大于根节点的元素
if(!isValidBSTRef(root->left, min, root->val))
{
break;
}
// 右子树的元素应该小于根节点的元素
if(!isValidBSTRef(root->right, root->val, max))
{
break;
}
bRet = true;
}while(false);
return bRet;
}
public:
bool isValidBST(TreeNode* root) {
return isValidBSTRef(root);
}
};