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 is binary search trees.
Idea: Middle sequence traversal. The current value is smaller than the previous.
BOOLIsvalidbst (treenode*root) {TreeNode* Ppre =NULL; TreeNode* Pcur =Root; Vector<treenode *>v; while(!v.empty () | | NULL! =pcur) { if(NULL! =pcur) {V.push_back (pcur); Pcur= pcur->Left ; } Else { if(Ppre! = NULL && v.back ()->val <= ppre->val)return false; Ppre=V.back (); V.pop_back (); Pcur= ppre->Right ; } } return true; }
Great God recursive version: Note that each time the value range of the left subtree is between the minimum and root values, the right subtree ranges between the roots and the maximum values.
Public classSolution { Public BooleanIsvalidbst (TreeNode root) {returnIsvalidbst (Root, Long.min_value, long.max_value); } Public BooleanIsvalidbst (TreeNode root,LongMinval,Longmaxval) { if(Root = =NULL)return true; if(Root.val >= maxval | | root.val <= minval)return false; returnIsvalidbst (Root.left, Minval, Root.val) &&Isvalidbst (Root.right, Root.val, maxval); }}
"Leetcode" Validate Binary Search Tree (middle)