二叉树 — 是否是满二叉树

文章介绍了如何判断一棵二叉树是否为满二叉树,提供了两种解法。第一种方法是通过计算节点数量和高度来判断;第二种方法是利用满二叉树的特性,即满二叉树的节点数等于2的层数次方减一。每种方法都采用递归处理二叉树的左右子树,并返回相关信息。
摘要由CSDN通过智能技术生成

分析:
共有两种解法:如果是满二叉树,其满足二叉树的节点数量 = 2 n − 1 2^n - 1 2n1 。其中n为二叉树的层数。
所以可以获取到该数的高度和总共的节点数,进行判断。
还可以根据判断左右子树是否是满二叉树,以及左右子树的层高来判断。

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

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

第一种解法

public static class Info1 {
        int height;
        boolean isFull;

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

    public static boolean isFull1(Node head) {
        if (head == null) {
            return true;
        }
        return process1(head).isFull;
    }

    public static Info1 process1(Node head) {
        if (head == null) {
            return new Info1(0, true);
        }

        Info1 leftInfo = process1(head.left);
        Info1 rightInfo = process1(head.right);

        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        boolean isFull = leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height;

        return new Info1(height, isFull);
    }

第二种解法

public static class Info2 {
        int height;
        int nodes;

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

    public static boolean isFull2(Node head) {
        if (head == null) {
            return true;
        }

        Info2 result = process2(head);

        return (1 << result.height) - 1 == result.nodes;
    }

    public static Info2 process2(Node head) {
        if (head == null) {
            return new Info2(0, 0);
        }

        Info2 leftInfo = process2(head.left);
        Info2 rightInfo = process2(head.right);

        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        int nodes = leftInfo.nodes + rightInfo.nodes + 1;

        return new Info2(height, nodes);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值