Leetcode-validate Binary Search Tree

Source: Internet
Author: User
Tags tree serialization

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.


OJ's binary tree serialization:

The serialization of a binary tree follows a level order traversal, where '# 'signiies a path Terminator where no node exists below.

Here's an example:

   1  /  2   3    /   4         5
The above binary tree is serialized "{1,2,3,#,#,4,#,#,5}".
/*** definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x ): val (x), left (null), right (null) {}*}; */struct treenode {int val; treenode * left; treenode * right; treenode (int x): Val (x), left (null), right (null) {}}; # If 1 // first method class solution {public: bool isvalidbst (treenode * root) {return checkbst (root, int_min, int_max);} PRIVATE: bool Che Ckbst (treenode * root, int min, int max) {If (root = NULL) return true; return min Val & root-> Val left, Min, root-> Val) & checkbst (root-> right, root-> Val, max) ;};# endif // 1 # If 0 // second method class solution {public: bool isvalidbst (treenode * root) {DFS (Root); For (INT I = 1; I = Result [I]) return false;} return true;} PRIVATE: STD: vector Result; void DFS (treenode * root) {If (root! = NULL) {DFS (root-> left); result. push_back (root-> Val); DFS (root-> right) ;}};# endif // 1


Leetcode-validate Binary Search Tree

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.