0
点赞
收藏
分享

微信扫一扫

算法与数据结构-满二叉树(FBT)

_karen 2022-01-22 阅读 198

什么是满二叉树(FBT)?

高度为h且该树的节点总个数为2^h-1

代码实现:

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

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

    public static class Info {
        public int height;
        public int nodes;

        public Info(int height, int nodes) {
            this.height = height;
            this.nodes = nodes;
        }
    }

    // 判断以head为根节点的树是否为满二叉树
    public static boolean isFBT(Node head) {
        if (head == null) {
            return true;
        }

        Info data = process(head);

        // 判断是否满足满二叉树特性,即判断2^h-1和总节点数的大小
        return data.nodes == (1 << data.height - 1);
    }

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

        Info leftData = process(x.left);
        Info rightData = process(x.right);
        // 1. 获取以x为根节点的树的高度
        int height = Math.max(leftData.height, rightData.height) + 1;

        // 2. 获取以x为根节点的树的总节点个数
        int nodes = leftData.nodes + rightData.nodes + 1;

        // 3. 返回以x为根节点的树的信息
        return new Info(height, nodes);
    }
}
举报

相关推荐

0 条评论