leetcode98. 验证二叉搜索树

一:题目

leetcode98. 验证二叉搜索树_第1张图片

二:上码

/**
 * 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 {
    
    public boolean isValidBST(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        int flag = 0;
        Order(root,list);
        
        for (int i  = 0; i < list.size(); i++) {
            if (i > 0 && list.get(i) <= list.get(i-1)) {
                flag = 1;
            } 
        }

        return flag == 0;

    }

    public void Order(TreeNode root,List<Integer> list) {
        if (root == null) return ;

        Order(root.left,list);
        list.add(root.val);
        Order(root.right,list);
    }

}

你可能感兴趣的