如何判断一颗二叉树完满二插树

方式一:容易理解但麻烦的做法

1、先写一个函数统计整个二叉树的最大深度(最大层数) l

2、再写一个函数去统计整个二叉树的节点个数 N

3、满二叉树满足N=2l-1

方式二:树型DP ---递归套路解决 

package Algorithms.tree;

public class IsFullTree {

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

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

    //主函数
    public static boolean isFullTree(Node head) {
        if (head == null) {
            return true;
        }
        Info data = process(head);
        System.out.println("树的层数为:"+data.height+"  树的节点数为:"+data.nodes);
        return data.nodes == ((1 << data.height) - 1);
    }

    //定义返回值类型:返回当前树的高度和节点个数
    public static class Info {
        public int height;
        public int nodes;

        public Info(int h, int n) {
            height = h;
            nodes = n;
        }
    }

    public static Info process(Node x) {
        if (x == null) {
            return new Info(0, 0);
        }

        Info leftDate = process(x.left);
        Info rightData = process(x.right);

        int height = Math.max(leftDate.height, rightData.height) + 1;
        int nodes = leftDate.nodes + rightData.nodes + 1;

        return new Info(height, nodes);
    }

    //测试
    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);

        System.out.println("是否为满二叉树:"+isFullTree(head));
    }
}

/**
 * 树的层数为:3  树的节点数为:7
 * 是否为满二叉树:true
 */
 

 

posted @ 2021-08-12 16:59  zh_小猿  阅读(42)  评论(0编辑  收藏  举报