[Leetcode] Validate Binary Search Tree, leetcodevalidate

Source: Internet
Author: User

[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);}};



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.