98. Validate Binary Search Tree (验证二叉搜索树,中序遍历)
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: 3 TreeNode* pre; // 因为后台数据有 int最小值测试用例,所以都改成了longlong最小值。 如果测试数据中有 longlong的最小值,怎么办?不可能在初始化一个更小的值了吧。 建议避免 初始化最小值,如下pre记录前一位节点: 4 bool isValidBST(TreeNode* root) { 5 if(root == nullptr) return true; 6 bool left = isValidBST(root->left); 7 if (pre!=nullptr && pre->val >= root->val) return false; 8 pre = root; 9 bool right = isValidBST(root->right); 10 return left&&right; 11 } 12 };
利用中序遍历,因为中序遍历的结果就是从小到大排好序的结果,如果是二叉搜索树的话。
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 }