LeetCode每日一题:判断是否是二叉排序树

问题描述

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.

问题分析

判断一棵树是不是二叉排序树,就看他的中序排列是不是递增的数列即可。

代码实现

private void getBSTNode(TreeNode root, ArrayList list) {
        if (root != null) {
            getBSTNode(root.left, list);
            list.add(root);
            getBSTNode(root.right, list);
        }
    }

    public boolean isValidBST(TreeNode root) {
        ArrayList list = new ArrayList<>();
        getBSTNode(root, list);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i - 1).val >= list.get(i).val) return false;
        }
        return true;
    }

你可能感兴趣的:(LeetCode每日一题:判断是否是二叉排序树)