Question
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.
Solution 1--Recursive
According to the question, we can write recursive statements. Note here whole left/right subtree should is smaller/greater than the root.
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public BooleanIsvalidbst (TreeNode root) { A if(Root = =NULL) - return true; - if(Root.left! =NULL&&!smallerthanroot (Root, Root.left)) the return false; - if(Root.right! =NULL&&!greaterthanroot (Root, root.right)) - return false; - if(Isvalidbst (Root.left) &&Isvalidbst (root.right)) + return true; - return false; + } A at Private Booleangreaterthanroot (TreeNode root, TreeNode child) { - if(Child.val <=root.val) - return false; - if(Child.left! =NULL) { - if(!greaterthanroot (Root, Child.left)) - return false; in } - if(Child.right! =NULL) { to if(!greaterthanroot (Root, child.right)) + return false; - } the return true; * } $ Panax Notoginseng Private Booleansmallerthanroot (TreeNode root, TreeNode child) { - if(Child.val >=root.val) the return false; + if(Child.left! =NULL) { A if(!smallerthanroot (Root, Child.left)) the return false; + } - if(Child.right! =NULL) { $ if(!smallerthanroot (Root, child.right)) $ return false; - } - return true; the } -}Solution 2--inorder traversal
Inorder traversal of BST is an ascending array. Java Stack
1 /**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten Public classSolution { One Public BooleanIsvalidbst (TreeNode root) { A //This problem can looked as inorder traversal problem - //inorder Traversal of BST is an ascending array -List<integer> Inorderresult =NewArraylist<integer>(); thestack<treenode> stack =NewStack<treenode>(); -TreeNode tmp =Root; - while(TMP! =NULL|| !Stack.empty ()) { - if(TMP! =NULL) { + Stack.push (TMP); -TMP =Tmp.left; +}Else { ATreeNode current =Stack.pop (); at Inorderresult.add (current.val); -TMP =Current.right; - } - } - //Traverse List - if(Inorderresult.size () < 1) in return true; - intmax = Inorderresult.get (0); to for(inti = 1; I < inorderresult.size (); i++) { + if(Inorderresult.get (i) >max) -Max =Inorderresult.get (i); the Else * return false; $ }Panax Notoginseng return true; - } the}
Validate Binary Search Tree Solution