左神算法——第18题——判断一棵二叉树是否是二叉搜索树

本文介绍了一种验证二叉搜索树(BST)正确性的方法,包括递归和非递归两种算法实现。通过中序遍历确保左子树<节点<右子树的性质,从而判断树是否为有效的BST。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉搜索树(BST,Binary Search Tree):对于一棵树上任何一个节点的子树,左子树 < 节点 < 右子树 。通常不出现重复节点,如果有重复节点,可以把它们的值压缩在一个节点的内部。

import java.util.Stack;

public class e05IsBST {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }
    //递归
    static int pre = Integer.MIN_VALUE;
    public static Boolean isBST(Node head) {
        boolean res = true;
        if (head == null) {
            return res;
        }
        isBST(head.left);
        if (head.value > pre) {
            pre = head.value;
        } else {
            res = false;
        }
        isBST(head.right);
        return res;
    }

    //非递归
    public static Boolean isBST2(Node head) {
        int pre = Integer.MIN_VALUE;
        if (head != null) {
            Stack<Node> stack = new Stack<>();
            while (!stack.isEmpty() || head != null) {
                if (head != null) {
                    stack.push(head);
                    head = head.left;
                } else {
                    head = stack.pop();
                    if (head.value > pre) {
                        pre = head.value;
                    } else {
                        return false;
                    }
                    head = head.right;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Node A=new Node(4);
        Node B=new Node(1);
        Node C=new Node(2);
        Node D=new Node(3);
//        Node E=new Node(1);
        A.left=B;
        B.left=C;
        B.right=D;
        System.out.println(isBST(A));
        System.out.println(isBST2(A));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值