leetcode -day26 Validate Binary Search Tree

66 篇文章 0 订阅
1、
﻿﻿

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.

class Solution {
public:
bool isValidBST(TreeNode *root) {
int minValue = INT_MIN;
int maxValue = INT_MAX;
return isValidBST(root,maxValue,minValue);
}
bool isValidBST(TreeNode *root,int maxValue,int minValue){
if(!root){
return true;
}
bool isLeft = true;
if(root->left){
if(root->left->val >= root->val || root->left->val <= minValue){
return false;
}
isLeft = isValidBST(root->left,root->val,minValue);
}
bool isRight = true;
if(root->right){
if(root->right->val <= root->val || root->right->val >= maxValue){
return false;
}
isRight = isValidBST(root->right,maxValue,root->val);
}
if(isLeft && isRight){
return true;
}else{
return false;
}
}
};


04-02 2714
07-02 177
09-24 524
08-04 2652
04-20 307

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

xiao囡囡

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。