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.
Topic: Given a binary tree, to determine whether it is a binary search tree, the binary search tree satisfies the requirements Zuozi all values are less than the current node value, the right subtree all the value is greater than the current node, and the subtree is also two fork search tree.
Problem Solving Ideas:
First, recursive verification, each node set an allowable range, the root node is of course all can, the other nodes to be greater than min and less than Max, and recursive validation of the left and right subtree to update min and Max.
-----binary Tree (0)/ 5 --------binary tree (1) / 6 20
As above, tree (1) is legal, but 6:10 is small, and 6 is located between 10~15, so this tree is not legal. That is, two values, Max, Min, are required to record the range of values that the current node should take. So what are the rules for the updates of Min and Max? For left dial hand tree, should be small root node, for right subtree, should be greater than the root node, for a node, its value should be the upper limit of Zuozi, the lower limit of the right subtree.
Take the tree above for example, the lower bound of node 15 is 10, the upper bound is null, recursive to the left subtree node 6, the lower bound is 10, the upper limit is 15, does not meet the range requirements, returns false.
Public BooleanIsvalidbst (TreeNode root) {returnDovalidate (Root,NULL,NULL); } Private Booleandovalidate (TreeNode root, Integer min, integer max) {if(Root = =NULL) { return true; } intval =Root.val; if(min! =NULL&& min >=val) { return false; } if(max! =NULL&& Max <=val) { return false; } returnDovalidate (Root.left, Min, val) &&dovalidate (Root.right, Val, Max); }
Second, ( recommended ) Intuitive, clear problem-solving ideas: Two forks the sequence traversal of the search tree should be incremental, so you only need to check if the sequence traversal sequences are ascending.
Public BooleanisValidBST2 (TreeNode root) {if(Root = =NULL) { return true; } List<Integer> list =NewArraylist<>(); Dovalidate (root, list); for(inti = 1; I < list.size (); i++) { if(List.get (i-1) >=List.get (i)) { return false; } } return true; } voidDovalidate (TreeNode node, list<integer>list) { if(node = =NULL) { return; } dovalidate (Node.left, list); List.add (Node.val); Dovalidate (node.right, list); }
Validate Binary Search Tree--leetcode