代码随想录——验证二叉搜索树(Leetcode98)

时间:2024-06-02 22:02:15
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { ArrayList<Integer> array = new ArrayList<>(); public boolean isValidBST(TreeNode root) { inOrder(root); for(int i = 1; i < array.size(); i++){ if(array.get(i) <= array.get(i - 1)){ return false; } } return true; } // 中序遍历 public void inOrder(TreeNode root){ if(root == null){ return ; } inOrder(root.left); array.add(root.val); inOrder(root.right); } }