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

二叉搜索树(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));
    }
}

你可能感兴趣的:(左神算法)