Leetcode 98. Validate Binary Search Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Validate Binary Search Tree

2. Solution

  • Recurrent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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 validate(root, nullptr, nullptr);
}

private:
bool validate(TreeNode* root, TreeNode* max, TreeNode* min) {
if(!root) {
return true;
}
if((min && root->val <= min->val) || (max && root->val >= max->val)) {
return false;
}
return validate(root->left, root, min) && validate(root->right, max, root);
}
};

Reference

  1. https://leetcode.com/problems/validate-binary-search-tree/description/
如果有收获,可以请我喝杯咖啡!