[Leetcode] Validate Binary Search Tree, leetcodevalidate
Given a binary tree, determine if it is a valid binary search tree (BST ).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Check whether a tree is a balanced binary tree. The nature of BST is listed above. At the beginning, I wrote a recursive method. The result is the INT_MAX and INT_MIN values. If these two values appear in the tree, this method is not feasible.
class Solution {public:bool isValidBST(TreeNode *root) {return check(root, INT_MAX, INT_MIN);}bool check(TreeNode *root, int max, int min){if (NULL == root) return true;if (root->val > min && root->val < max){return check(root->left, root->val, min) && check(root->right, max, root->val);}else return false;}};
After turning over the Internet for a long time, I found that many of the previous AC code was written in this way, which indicates that leetcode may have updated test cases and added INT_MAX and INT_MIN detection, the code is no longer accessible (just like the reverse integar question ). The time complexity is O (n), and the space complexity is O (0 ).
In this case, this approach will not work. It can only start from another nature of BST, and traverse this tree in ascending order. If this tree is BST, The traversal result is exactly in ascending order, in this way, the space complexity also reaches O (n ).
class Solution {public:bool isValidBST(TreeNode *root) {vector<int> result;inorder(root, result);for (int i = 1; i < result.size(); i++){if (result[i - 1] >= result[i]) return false;}return true;}void inorder(TreeNode *root,vector<int> &result){if (!root) return;if (root->left) inorder(root->left, result);result.push_back(root->val);if (root->right) inorder(root->right, result);}};