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 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / \ 2 3
Binary tree [1,2,3]
, return false.
题意是要我们判断这是否是一个合法的二叉搜索树,合法的定义是左子树的所有节点都要小于根节点,右子树的所有节点都要小于根节点,我就想着,给每个子树都设立一个取值范围,那么判断大小的时候就很简单了,所以代码如下。
Code:
/**
* 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) {
return isValidBST(root, INT_MIN, INT_MAX);
}
bool isValidBST(TreeNode *root, int min, int max) {
if (!root) {
return true;
}
return root -> val > min && root -> val < max && isValidBST(root -> left, min, root -> val) && isValidBST(root -> right, root -> val, max);
}
};
但是这个代码没有过,因为以下的样例:
[2147483647]
也就是说,当节点的值为INT_MAX或者INT_MIN时,就会出错。所以这种办法只是一种比较取巧的办法,但是可以由这种办法来延伸出另一个办法:范围值是最小点和最大点之间。想法是参考了leetcode上面的discuss的人的算法思路。代码如下:
Code(LeetCode运行9ms)
/**
* 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) {
return isValidBST(root, NULL, NULL);
}
bool isValidBST(TreeNode *root, TreeNode *min, TreeNode *max) {
if (!root) {
return true;
}
if (min && root -> val <= min -> val || max && root -> val >= max -> val) {
return false;
}
return isValidBST(root -> left, min, root) && isValidBST(root -> right, root, max);
}
};