二叉树——统计完全二叉树的节点数

1. 统计完全二叉树的节点数

1.1. 问题

如题。

注:完全二叉树表示二叉树内没有空隙;满二叉树是一种特殊的完全二叉树,其所有的叶子节点均在同一层上。

1.2. 思路

方法一:遍历

最简单的做法:遍历一次。时间复杂度为O(n)。

方法二:高度探查

用高度探查方式的时间复杂度为O(h^2)。

当我们拿到一个完全二叉树时,其高度等于其左边界的长度。

  • 当其左子树的高度和右子树的高度相同时,表示它是一个满二叉树
  • 当其左子树的高度大于右子树的高度时,那么其右子树是满二叉树,继续探查其左子树。

1.3. 代码

第一次写的时候忘了把当前节点给算上,并且没有使用移位运算,在移位运算时,没有加括号。。。

    public static int countCBTreeNodes(TreeNode<Integer> head) {
        if (head == null) return 0;
        int leftHeight = height(head.left);
        int rightHeight = height(head.right);
        int res = 0;
        if (leftHeight == rightHeight) {
            res = (1 << leftHeight) + countCBTreeNodes(head.right);
        } else {
            res = countCBTreeNodes(head.left) + (1 << rightHeight);
        }
        return res;
    }

    public static int height(TreeNode<Integer> head) {
        int res = 0;
        while (head != null) {
            res++;
            head = head.left;
        }
        return res;
    }
posted @ 2022-05-11 19:15  迈吉  阅读(57)  评论(0编辑  收藏  举报