LeetCode Validate Binary Search Tree

Source: Internet
Author: User

Validate Binary Search Tree

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.

    Confused what"{1,#,2,3}"Means? > Read more on how binary tree is serialized on OJ.

    This is a difficulty: You must set the limit values on both sides of the node.

    I have absorbed the suggestions from the LeetCode Forum, instead of INT_MAX and INT_MIN. Here I use LLONG_MIN and LLONG_MAX.

    If INT_MIN is used, when the value of the first left subtree is INT_MIN, it is regarded as false, which is actually true.

    Although leetcode does not test this situation, sound programs are always the best.

    Class Solution {public: bool isValidBST (TreeNode * root) {return validBST (root) ;}// Note: Do not forget the boundary on both sides: leftMax and rightMax settings/* I dont think it's a good idea to use int to represent the up and low bound of a TreeNode, INT_MIN and INT_MAX maybe used by TreeNode. we can use double or just the TreeNode itself. */bool validBST (TreeNode * root, long leftMax = LLONG_MIN, long rightMax = LLONG_MAX) {if ( ! Root) return true; if (! Root-> left &&! Root-> right) return true; if (root-> left & (root-> left-> val> = root-> val | root-> left-> val <= leftMax) return false; if (root-> right & (root-> right-> val <= root-> val | root-> right-> val> = rightMax) return false; return validBST (root-> left, leftMax, root-> val) & validBST (root-> right, root-> val, rightMax );}};










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.