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