98. 验证二叉搜索树

My Solution

利用二叉搜索树的中序遍历一定是有序的解决

  1. class Solution {
  2. List<Integer> list = new ArrayList<>();
  3. public boolean isValidBST(TreeNode root) {
  4. visit(root);
  5. if (list.size() <= 1) {
  6. return true;
  7. }
  8. for (int i = 1; i < list.size(); i++) {
  9. if (list.get(i - 1) >= list.get(i))
  10. return false;
  11. }
  12. return true;
  13. }
  14. public void visit(TreeNode root) {
  15. if (root == null)
  16. return ;
  17. visit(root.left);
  18. list.add(root.val);
  19. visit(root.right);
  20. }
  21. }

递归写法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public boolean isValidBST(TreeNode root) {
  18. return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
  19. }
  20. public boolean isValidBST(TreeNode root, long lower, long upper) {
  21. if (root == null) {
  22. return true;
  23. }
  24. if (root.val >= upper || root.val <= lower) {
  25. return false;
  26. }
  27. return isValidBST(root.left, lower, root.val) && isValidBST(root.right, root.val, upper);
  28. }
  29. }