《程序员代码面试指南》第三章 二叉树问题 判断一个树是搜索二叉树和完全二叉树

题目

判断一个树是搜索二叉树和完全二叉树

java代码

package com.lizhouwei.chapter3;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Description:判断一个树是搜索二叉树和完全二叉树
 * @Author: lizhouwei
 * @CreateDate: 2018/4/15 9:31
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter3_15 {

    public boolean isBST(Node head) {
        if (head == null) {
            return false;
        }
        return inOrder(head);
    }

    //用中序遍历
    public boolean inOrder(Node head) {
        Node pre = 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 (pre != null && pre.value > head.value) {
                    return false;
                }
                pre = head;
                head = head.right;
            }
        }
        return true;
    }

    public boolean isCBT(Node head) {
        boolean leaf = false;
        Node left = null;
        Node right = null;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(head);
        while (!queue.isEmpty()) {
            head = queue.poll();
            left = head.left;
            right = head.right;
            //不符合完全二叉树的情况有两种
            // 1.左子节点为空,右子节点不为空
            // 2.前面已经出现过右子节点为空的节点,此时左子节点或者右子节点任意不为空
            if (left == null && right != null || (leaf && (left != null || right != null))) {
                return false;
            }
            if (left != null) {
                queue.offer(left);
            }
            if (right != null) {
                queue.offer(right);
            } else {
                leaf = true;//含有右子节点为空的节点
            }
        }
        return true;
    }

    //测试
    public static void main(String[] args) {
        Chapter3_15 chapter = new Chapter3_15();
        int[] arr1 = {1, 2, 3, 4, 6, 7, 0, 9, 5};
        Node head1 = NodeUtil.generTree(arr1, 0, arr1.length - 1);
        boolean res1 = chapter.isBST(head1);
        System.out.println("arr1{1, 2, 3, 4, 6, 7, 0, 9, 5}是否为二叉搜索树:" + res1);
        int[] arr2 = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        Node head2 = NodeUtil.generTree(arr2, 0, arr2.length - 1);
        boolean res2 = chapter.isBST(head2);
        System.out.println("arr2{1, 2, 3, 4, 5, 6, 7, 8, 9}是否为二叉搜索树:" + res2);
        int[] arr3 = {1, 2, 3, 4, 6, 7, 8, 9, 5};
        Node head3 = NodeUtil.generTree(arr3, 0, arr3.length - 1);
        boolean res3 = chapter.isCBT(head3);
        System.out.println("arr3{1, 2, 3, 4, 6, 7, 8, 9, 5}是否为完全二叉树:" + res3);
        int[] arr4 = {1, 3, 4, 5, 6, 7, 8};
        Node head4 = NodeUtil.generTree(arr4, 0, arr4.length - 1);
        boolean res4 = chapter.isCBT(head4);
        System.out.println("arr4{1, 3, 4,5, 6, 7, 8}是否为完全二叉树:" + res4);
    }
}

结果

原文地址:https://www.cnblogs.com/lizhouwei/p/8845959.html