LeetCode – Refresh – Valid Binary Search Tree
2015-03-25 08:00
288 查看
Inorder traversal the tree and compare one by one.
Another method is use BST properties. Then constrains two boundaries. But this does not work not. There are couple edge cases related with INT_MAX and INT_MIN;
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void getTree(vector<int> &result, TreeNode *root) { if (!root) return; getTree(result, root->left); result.push_back(root->val); getTree(result, root->right); } bool isValidBST(TreeNode *root) { if (!root) return true; vector<int> result; getTree(result, root); for (int i = 0; i < result.size()-1; i++) { if (result[i] >= result[i+1]) return false; } return true; } };
Another method is use BST properties. Then constrains two boundaries. But this does not work not. There are couple edge cases related with INT_MAX and INT_MIN;
/** * 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 isValid(TreeNode *root, int lMin, int lMax) { if (!root) return true; if (root->val <= lMin || root->val >= lMax) return false; return isValid(root->left, lMin, root->val) && isValid(root->right, root->val, lMax); } bool isValidBST(TreeNode *root) { if (!root) return true; return isValid(root, INT_MIN, INT_MAX); } };
相关文章推荐
- LeetCode – Refresh – Unique Binary Search Tree
- leetcode 94: Valid Binary Search Tree
- LeetCode – Refresh – Unique Binary Search Tree II
- leetcode 94: Valid Binary Search Tree
- 【Leetcode】Valid Binary Search Tree
- leetcode-valid binary search tree
- LeetCode 98: Valid Binary Search Tree
- LeetCode – Refresh – Recover Binary Search Tree
- [LeetCode/LinkedIn] Valid Binary Search Tree
- leetcode : valid binary search tree
- LeetCode – Refresh – Convert Sorted Array to Binary Search Tree
- LeetCode – Refresh – Convert Sorted List to Binary Search Tree
- LeetCode---Recover Binary Search Tree
- leetcode第40题(convert-sorted-list-to-binary-search-tree)
- [算法分析与设计] leetcode 每周一题: Validate Binary Search Tree
- LeetCode(99)Recover Binary Search Tree
- leetcode - Convert Sorted List to Binary Search Tree
- LeetCode | Convert Sorted List to Binary Search Tree(链表转换成二叉搜索树)
- 【Leetcode】Two Problems: Convert Sorted Array/List to Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree