zoukankan      html  css  js  c++  java
  • 判断二叉树是不是满二叉树

    package algorithm.tree;

    /**
    * 判断二叉树是不是满二叉树
    */
    public class IsFull {

    public static boolean isFull(Node node) {
    return process(node).isFull;
    }

    private static ResultInfo process(Node node) {
    if (node == null) {
    return new ResultInfo(true, 0);
    }
    ResultInfo leftInfo = process(node.left);
    ResultInfo rightInfo = process(node.right);
    boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;
    int height = Math.max(leftInfo.height, rightInfo.height) + 1;
    return new ResultInfo(isFull, height);
    }

    public static boolean isFull1(Node head) {
    if (head == null) {
    return true;
    }
    int height = h(head);
    int nodes = n(head);
    return (1 << height) - 1 == nodes;
    }

    public static int h(Node head) {
    if (head == null) {
    return 0;
    }
    return Math.max(h(head.left), h(head.right)) + 1;
    }

    public static int n(Node head) {
    if (head == null) {
    return 0;
    }
    return n(head.left) + n(head.right) + 1;
    }

    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
    return generate(1, maxLevel, maxValue);
    }

    // for test
    public static Node generate(int level, int maxLevel, int maxValue) {
    if (level > maxLevel || Math.random() < 0.5) {
    return null;
    }
    Node head = new Node((int) (Math.random() * maxValue));
    head.left = generate(level + 1, maxLevel, maxValue);
    head.right = generate(level + 1, maxLevel, maxValue);
    return head;
    }

    public static void main(String[] args) {
    int maxLevel = 5;
    int maxValue = 100;
    int testTimes = 1000000;
    for (int i = 0; i < testTimes; i++) {
    Node head = generateRandomBST(maxLevel, maxValue);
    boolean isFull1 = isFull1(head);
    boolean isFull = isFull(head);
    if (isFull1 != isFull) {
    System.out.println("Oops!");
    }
    }
    System.out.println("finish!");
    }

    /**
    * 向左右子树索要信息
    */
    public static class ResultInfo {

    // 是否是满二叉树
    public boolean isFull;

    // 树高度
    public int height;

    public ResultInfo(boolean isFull, int height) {
    this.isFull = isFull;
    this.height = height;
    }

    }

    /**
    * 二叉树结构
    */
    public static class Node {

    public int value;

    public Node left;

    public Node right;

    public Node(int value) {
    this.value = value;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    皇帝的用人之道,这一点古今皆同
    sharepoint打包
    powershellbegin
    taxonomy
    powershelluninstall webapplication
    面试题
    字符串处理
    在页面中插入视频时的文件夹命名问题
    process object
    扩展名显示与隐藏
  • 原文地址:https://www.cnblogs.com/laydown/p/12994481.html
Copyright © 2011-2022 走看看