代码改变世界

leetcode - Validate Binary Search Tree

2013-11-10 11:14  张汉生  阅读(141)  评论(0编辑  收藏  举报

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 #include <limits.h>
11 class Solution {
12 public:
13     bool isValid(TreeNode * node, int min, int max){
14         if (node==NULL)
15             return true;
16         if (node->val >= max || node->val <= min)
17             return false;
18         return isValid(node->left, min, node->val) && isValid(node->right, node->val, max);
19     }
20     bool isValidBST(TreeNode *root) {
21         // IMPORTANT: Please reset any member data you declared, as
22         // the same Solution instance will be reused for each test case.
23         return isValid(root, INT_MIN, INT_MAX);
24     }
25 };