LeetCode 222 Count Complete Tree Nodes

题目描述

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

分析

如果层序遍历,时间复杂度是O(n)。可以使用类似二分查找的方法,因为二叉树是完全二叉树,计算leftHeight和rightHeight,最大相差1,然后递归求解。

代码

    public int countNodes(TreeNode root) {

        if (root == null) {
            return 0;
        }

        int leftHeight = 0;
        int rightHeight = 0;

        // 计算leftHeight
        TreeNode p = root;
        while (p != null) {
            p = p.left;
            leftHeight++;
        }

        // 计算rightHeight
        p = root;
        while (p != null) {
            p = p.right;
            rightHeight++;
        }

        // 如果相等,满足2^n-1
        if (leftHeight == rightHeight) {
            return (1 << leftHeight) - 1;
        }

        return 1 + countNodes(root.left) + countNodes(root.right);

    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50259309
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞