[LeetCode]Validate Binary Search Tree
2013-06-03 09:09
260 查看
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { //hint: when involved with BST, always remember that special effect of in-order traversal //1. pass down the low and high limits from node to node //2. we can always do an in-order traversal of BST, then the value we visited should be in increasing order, //so we can check the previous is smaller than current value public: bool isBSTHelper(TreeNode* root, int low, int high) { if(!root) return true; if (low < root->val && high > root->val) return isBSTHelper(root->left, low, root->val) && isBSTHelper(root->right, root->val, high); else return false; } bool isBSTHelper(TreeNode* root, int& prev) { if(!root) return true; return isBSTHelper(root->left, prev) && (root->val > prev) && ((prev = root->val)||true) && isBSTHelper(root->right, prev); } bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function //first solution //return isBSTHelper(root, INT_MIN, INT_MAX); //second solution int prev = INT_MIN; return isBSTHelper(root, prev); } };
second time
/** * 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 isValidBSTUtil(TreeNode* root, int mmin, int mmax) { if(root == NULL) return true; if(mmin < root->val && root->val < mmax) { return isValidBSTUtil(root->left, mmin, min(mmax, root->val)) && isValidBSTUtil(root->right, max(mmin, root->val), mmax); } else return false; } bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function int mmin = INT_MIN; int mmax = INT_MAX; return isValidBSTUtil(root, mmin, mmax); } };
相关文章推荐
- LeetCode刷题笔录 Validate Binary Search Tree
- [C++]LeetCode: 122 Validate Binary Search Tree (是否是合法BST树)
- LeetCode 98: Validate Binary Search Tree
- leetcode笔记:Validate Binary Search Tree
- LeetCode098 Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode - 98 - Validate Binary Search Tree
- LeetCode-98. Validate Binary Search Tree
- Validate Binary Search Tree (leetcode)
- LeetCode_Validate Binary Search Tree
- Validate Binary Search Tree - LeetCode
- Leetcode优化:Validate Binary Search Tree
- *(leetcode)Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- leetcode 94: Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [leetcode] 98 Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- Validate Binary Search Tree——LeetCode
- Leetcode-Validate Binary Search Tree