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.
解题思路
判断一个二叉树是否为二分查找树。需要注意的是,左子树的所有节点都要比根节点小,而非只是其左孩子比其小,右子树同样。
思路一:根据定义判断。从根节点开始递归所有的节点,对每个节点分别遍历其左右子树,判断是否满足其左子树的最大值比其小,右子树的最小值比其大。时间复杂度 O(n2) 。
思路二:使用递归求解。在递归时传入两个额外参数,一个是左界,一个是右界,节点的值必须在两个界的中间;同时在递归判断左子树和右子树时更新左右界。代码如下:
/**
* 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:
bool inRange(TreeNode *root, long long min_val, long long max_val) {
if (root == NULL) return true;
if (root->val <= min_val || root->val >= max_val) {
return false;
}
bool leftInRange = inRange(root->left, min_val, root->val);
bool rightInRange = inRange(root->right, root->val, max_val);
return leftInRange && rightInRange;
}
public:
bool isValidBST(TreeNode* root) {
// Note: 需要把 INT_MIN 和 INT_MAX 转化成 long long
return inRange(root, (long long)INT_MIN - 1, (long long)INT_MAX + 1);
}
};
思路三:利用二叉搜索树中序遍历的结果是一个有序递增序列的性质,在中序遍历的过程中判断左子树、当前节点和右子树是否满足条件,时间复杂度为 O(n) 。
/**
* 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 == NULL) return true;
// 将 INT_MIN 转换成 long long 避免溢出
long long pre = (long long)INT_MIN - 1;
// 中序遍历
TreeNode *p = root;
stack<TreeNode *> nodeStack;
while (p != NULL || !nodeStack.empty()) {
while (p != NULL) {
nodeStack.push(p);
p = p->left;
}
if (!nodeStack.empty()) {
p = nodeStack.top();
nodeStack.pop();
if (pre >= (long long)p->val) {
// 不满足“中序遍历应得到一个递增序列”
return false;
}
pre = p->val;
p = p->right;
}
}
return true;
}
};