Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
一开始是这样做的:
1 class Solution { 2 public: 3 bool isValidBST(TreeNode* root) { 4 return checkValid(root, INT_MIN, INT_MAX); 5 } 6 7 bool checkValid(TreeNode * root, int left, int right) 8 { 9 if(root == NULL) 10 return true; 11 return(root->val > left && root->val < right && checkValid(root->left, left, root->val) ] 12 && checkValid(root->right, root->val, right)); 13 } 14 };
然而并不能通过,因为leetCode增加了两个新的测试用例,把INT_MAX以及INT_MIN也囊括进去了。
那么就只好用中序遍历的方法来了,代码如下:
1 class Solution { 2 public: 3 bool isValidBST(TreeNode* root) { 4 inOrder(root); 5 int sz = res.size(); 6 if(sz < 2) return true; 7 for(int i = 1; i < sz; ++i){ 8 if(res[i] <= res[i - 1]) 9 return false; 10 } 11 return true; 12 } 13 14 void inOrder(TreeNode * root) 15 { 16 if(!root) return; 17 if(root->left) inOrder(root->left); 18 res.push_back(root->val); 19 if(root->right) inOrder(root->right); 20 } 21 private: 22 vector<int> res; 23 };
当然上面的也可以采用迭代的方式来做,代码这里就不贴了
LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)
原文:http://www.cnblogs.com/-wang-cheng/p/4908685.html