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 be binary search trees.
Example 1:
2 / 1 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / 2 3Binary tree
[1,2,3]
, return false.利用中序遍历,因为中序遍历的结果就是从小到大排好序的结果,如果是二叉搜索树的话。
1 class Solution { 2 public boolean isValidBST(TreeNode root) { 3 if(root==null) return true; 4 TreeNode cur = root; 5 TreeNode pre = null; 6 Stack<TreeNode> stack = new Stack<TreeNode>(); 7 while(cur!=null || !stack.isEmpty()){ 8 while(cur!=null){ 9 stack.push(cur); 10 cur = cur.left; 11 } 12 cur = stack.pop(); 13 if(pre!=null && pre.val>=cur.val) return false; 14 pre =cur; 15 cur=cur.right; 16 } 17 return true; 18 19 } 20 21 }
利用递归,需要将最大值最小值传下去。
1 class Solution { 2 public boolean isValidBST(TreeNode root) { 3 return test(root,Long.MIN_VALUE,Long.MAX_VALUE); 4 } 5 private boolean test(TreeNode root,long min,long max){ 6 if(root==null) return true; 7 if(root.val>=max ||root.val<=min) return false; 8 return test(root.left,min,root.val) && test(root.right,root.val,max); 9 } 10 }