|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * struct TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode *left; |
| 6 | + * TreeNode *right; |
| 7 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 8 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 10 | + * }; |
| 11 | + */ |
| 12 | +class Solution { |
| 13 | +public: |
| 14 | + bool isValidBST(TreeNode* root){ |
| 15 | + stack <TreeNode*> st; |
| 16 | + TreeNode* prev = NULL; |
| 17 | + |
| 18 | + while (root || !st.empty()){ |
| 19 | + while (root){ |
| 20 | + st.push(root); |
| 21 | + root = root->left; |
| 22 | + } |
| 23 | + root = st.top(); |
| 24 | + st.pop(); |
| 25 | + |
| 26 | + if(prev && root->val<=prev->val){ |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + prev = root; |
| 31 | + root = root->right; |
| 32 | + } |
| 33 | + return true; |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +/** |
| 40 | + * Definition for a binary tree node. |
| 41 | + * struct TreeNode { |
| 42 | + * int val; |
| 43 | + * TreeNode *left; |
| 44 | + * TreeNode *right; |
| 45 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 46 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 47 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 48 | + * }; |
| 49 | + */ |
| 50 | +class Solution { |
| 51 | +public: |
| 52 | + bool isValidBST(TreeNode* root){ |
| 53 | + return isValidBSTHelper(root, LLONG_MIN, LLONG_MAX); |
| 54 | + } |
| 55 | + bool isValidBSTHelper(TreeNode* root, long min, long max){ |
| 56 | + if (root == NULL) return true; |
| 57 | + if (root->val<=min || root->val>=max) return false; |
| 58 | + return isValidBSTHelper(root->left, min, root->val) && isValidBSTHelper(root->right, root->val, max); |
| 59 | + } |
| 60 | +}; |
0 commit comments