题意:给定一棵二叉树,写程序判断这颗二叉树是否为合法的二分查找树(对于节点root,其所有左子树中节点都满足 node.val < root.val,其所有右子树中节点都满足 node.val > root.val)
转载请注明出处:http://blog.youkuaiyun.com/sunny606
C++:
/**
* 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 isValidBSTHelper(root, numeric_limits<long long>::min(), numeric_limits<long long>::max());
}
bool isValidBSTHelper(TreeNode* root, long long int s, long long int e) {
if(!root) {
return true;
}
if(s < root->val && root->val < e) {
if(root->left && !isValidBSTHelper(root->left, s, root->val)) {
return false;
}
if(root->right && !isValidBSTHelper(root->right, root->val, e)) {
return false;
}
return true;
} else {
return false;
}
}
};
javascript:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isValidBSTHelper = function(root, greater2x, less2x) {
if(root === null) {
return true;
}
if(less2x !==null && !less2x(root.val)) {
return false;
}
if(greater2x !==null && !greater2x(root.val)) {
return false;
}
var greater2this = function(x){
return x > root.val;
}
var less2this = function(x) {
return x < root.val;
}
if(root.left !==null && !isValidBSTHelper(root.left, greater2x, less2this)) {
return false;
}
if(root.right !==null && !isValidBSTHelper(root.right, greater2this, less2x)) {
return false;
}
return true;
}
var isValidBST = function(root) {
return isValidBSTHelper(root, null, null);
};