The problem:
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.
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 ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
. My First solution (wrong):
Public classSolution { Public BooleanIsvalidbst (TreeNode root) {if(Root = =NULL) return true; returnhelper (root); } Private BooleanHelper (TreeNode temp_root) {if(Temp_root = =NULL) return true; if(Temp_root.left! =NULL) { if(Temp_root.left.val >=temp_root.val)return false; } if(Temp_root.right! =NULL) { if(Temp_root.right.val <=temp_root.val)return false; } returnHelper (Temp_root.left) &&Helper (temp_root.right); } }
Analysis:
The recursion can only guarantee the comparsion between the temp_root with it's both direct children.
But the binary tree requries all left Sub-Tree's elements should less than temp_root, and all right sub-tree ' s elements sh Ould greater than temp_root.
Consider the case: {10, 5, 15, #, #, 6, 10}
The right-is:
The idea behind this problem are using the order properity of inorder traversal on binary search tree.
Key:if a tree is a binary tree, the inorder traversal on it must leads to an order series (ascending).
Binary Tree <=====> (inorder traversal) ordered array (ascending)
Thus, by using inorder traversal on the tree, we could compare each element in the series array with its previous element. (This could is achieved by using a Arraylist) This is cool!!!
At all element, we use following recursion rule:
1. Valid left & right sub-trees.
2. Check the current node's valid against its previous node. (Inorder traversal)
But, since we use the inorder traversal, we could write it in the following-in-a-do:
1. Check left sub-tree ' s validation.
2. Compare the current node ' s against it previous node.
3. Check right sub-tree ' s validation.
The right solution:
Public classSolution { Public BooleanIsvalidbst (TreeNode root) {if(Root = =NULL) return true; ArrayList<TreeNode> pre =NewArraylist<treenode> (); Pre.add (NULL); returnHelper (root, pre); } Private BooleanHelper (TreeNode Temp_root, arraylist<treenode>pre) { if(Temp_root = =NULL) return true; BooleanLeft_flag; BooleanRight_flag; Left_flag=Helper (temp_root.left, pre); if(Pre.get (0)! =NULL&& pre.get (0). Val >=temp_root.val)//must be strict less than, otherwise it's invalid return false; Pre.set (0, Temp_root); Right_flag=Helper (temp_root.right, pre); returnLeft_flag &&Right_flag; }}
[Leetcode#98] Validate Binary Search Tree