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 3
Binary tree [2,1,3]
, return true.
Example 2:
1 / \ 2 3
Binary tree [1,2,3]
, return false.
Fancy code,参考了discussion
思路:一个valid binary search tree, root肯定要处于Integer.MAX_VALUE和Integer.MIN_VALUE之间,不然无法形成bst.然后再检查左右子树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isValidBST(TreeNode root) { return dfs(root,Long.MIN_VALUE, Long.MAX_VALUE); } public boolean dfs(TreeNode root,long min,long max) { if(root==null) { return true; } if(root.val>=max||root.val<=min) { return false; } return dfs(root.left,min,root.val)&&dfs(root.right,root.val,max); } }
method 2。FROM DISCUSSION
用全局变量记录之前的root,之前的root的left node就是现在的root。
public class Solution { TreeNode pre = null; public boolean isValidBST(TreeNode root) { return inOrder(root); } public boolean inOrder(TreeNode root){ if(root==null) return true; if(!inOrder(root.left)) return false; if(pre==null){ pre= new TreeNode(root.val); }else{ if(root.val<=pre.val) return false; pre.val=root.val; } return inOrder(root.right); } }