判断是不是binary search tree-leetcode# JobHunting - 待字闺中
x*e
1 楼
在leetcode上判断一个二叉树是不是binary search tree,用in order traversal方法
,结果{-1,0}等test case通不过。上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int last_val = INT_MIN;
class Solution {
public:
bool isValidBST(TreeNode *root) {
if (root == NULL) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (root->val <= last_val) {
return false;
}
last_val = root->val;
if (!isValidBST(root->right)) {
return false;
}
return true;
}
};
,结果{-1,0}等test case通不过。上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int last_val = INT_MIN;
class Solution {
public:
bool isValidBST(TreeNode *root) {
if (root == NULL) {
return true;
}
if (!isValidBST(root->left)) {
return false;
}
if (root->val <= last_val) {
return false;
}
last_val = root->val;
if (!isValidBST(root->right)) {
return false;
}
return true;
}
};