【每日阅读】2020年11月17日-验证二叉搜索树

思路:中序遍历时,BST是升序的。

package algorithm.tree;

public class BstVerify {
    private static Integer lastNum = null;

    public static void main(String[] args) {
        TreeNode root = getTree();

        System.out.println("是BST: " + midVerify(root));
    }

    /**
     * 使用中序遍历的方式验证是否是BST
     */
    private static boolean midVerify(TreeNode root) {
        if (root == null) {
            return true;
        }

        if (!midVerify(root.left)) {
            return false;
        }

        if (lastNum != null && lastNum >= root.val) {
            return false;
        }

        lastNum = root.val;

        if (!midVerify(root.right)) {
            return false;
        }

        return true;
    }

    /**
     *     5
     *    / \
     *   2   6
     *  / \
     * 1   4
     *    /
     *   3
     */
    private static TreeNode getTree() {
        TreeNode root = new TreeNode(5);

        root.setLeft(new TreeNode(2));
        root.setRight(new TreeNode(6));

        root.getLeft().setLeft(new TreeNode(1));
        root.getLeft().setRight(new TreeNode(4));

        root.getLeft().getRight().setLeft(new TreeNode(3));

        return root;
    }
}

原创文章,作者:geekgao,如若转载,请注明出处:https://www.geekgao.cn/archives/2693

(0)
geekgaogeekgao博主
上一篇 2020年11月14日
下一篇 2020年11月19日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

GitHub
分享本页
返回顶部

Warning: error_log(/usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/#log/log-1623.txt): failed to open stream: No such file or directory in /usr/local/lighthouse/softwares/wordpress/wp-content/plugins/spider-analyser/spider.class.php on line 2900