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 keysLessThe node's key.
- The right subtree of a node contains only nodes with keysGreaterThe node's key.
- Both the left and right Subtrees must also be binary search trees.
Confused what"{1,#,2,3}"
Means?
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}"
A binary tree is given to determine whether the tree is a binary sorting tree. Binary sorting tree rules: (1) if the left subtree exists, the values of all nodes in the left subtree are smaller than the values of the root node. (2) If the right subtree exists, the value of all nodes in the right subtree must be greater than the value of the root node. (3) If a tree with root nodes is a binary sorting tree, the left and right subtree must also be a binary sorting tree. First, I came up with a solution: I have previously written to the process of creating a binary tree with queues. The process is similar to the sequential traversal of a binary tree. Therefore, we can see in turn that the sequence composed of the result of the sequential traversal of the binary sorting tree should be ordered. Based on this idea, you can get the following code:
Class solution {public: bool isvalidbst (treenode * root) {If (! Root | (! Root-> left &&! Root-> right) return true; vector <int> VI; VI. clear (); // uses non-recursive methods to traverse the tree in the central order and store the result in the VI array stack <treenode *> S; treenode * TMP = root; while (! S. empty () | TMP) {If (TMP) {S. push (TMP); TMP = TMP-> left;} else {TMP = S. top (); S. pop (); VI. push_back (TMP-> Val); TMP = TMP-> right ;}// you can determine the result of the Middle-order traversal. Note that duplicate numbers for (INT I = 1; I <VI. size (); I ++) {If (VI [I] <= VI [I-1]) return false;} return true ;}};
Reprint please indicate the source: http://www.cnblogs.com/double-win/ thank you!