while写成if debug了半天。
/**
* Definition for binary tree
* 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) return true;
if(!isValidBST(root->left)) return false;
if(!isValidBST(root->right)) return false;
TreeNode* tmp,*pre;
if(root->left) {
tmp = root->left; pre=root;
while(tmp) {
pre = tmp;
tmp =tmp->right;
}
if(pre!=root&&pre->val>=root->val) return false;
}
if(root->right) {
tmp = root->right; pre = root;
while(tmp) {
pre = tmp;
tmp = tmp->left;
}
if(pre!=root&&pre->val<=root->val) return false;
}
return true;
}
};
本文介绍了一种验证二叉树是否为有效的二叉搜索树的方法。通过递归检查每个节点的左子树和右子树,并确保所有节点值符合二叉搜索树的定义。
518

被折叠的 条评论
为什么被折叠?



