9. Count Complete Tree Nodes

Link to the problem

Description

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

Example

Input: [1,2,3,4], Output: 4
Input: [1,2,3,4,5,6], Output: 6

Idea

Recursion. Compare the height of the left subtree and right subtree. If they are equal, then the left subtree is full, recurse on the right subtree. Otherwise, the right subtree is full, recurse on the left subtree.

Solution

class Solution {
public:
    int countNodes(TreeNode* root) {
        if (!root) return 0;
        else if (!root->left) return 1;
        else if (!root->right) return 2;
        int leftHeight = 0, rightHeight = 0;
        TreeNode *left = root->left, *right = root->right;
        while (left) {
            leftHeight++;
            left = left->left;
        }
        while (right) {
            rightHeight++;
            right = right->left;
        }
        if (leftHeight == rightHeight) {
            return 1 + ((1 << leftHeight) - 1) + countNodes(root->right);
        } else {
            return 1 + countNodes(root->left) + ((1 << rightHeight) - 1);
        }
    }
};

18 / 18 test cases passed.
Runtime: 43 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转眼学期就要过去一半了,总是安排学生写总结作业,我也要身体力行,总结下, 因为将要迎来半个月的时间周,比赛增加,因...
    悠悠99阅读 244评论 0 0
  • 2017.8.12晴 亲爱的,请不要埋怨自己的代理没死气沉沉,没有激情;不积极,没有忠诚度,没有战斗力!当她加进来...
    明珠王蕾阅读 284评论 0 0
  • 作为一名骑行爱好者,前年和朋友一起骑行了西藏,完成了西藏行的梦想,虽然这期间经历了三次死亡,但依然觉得骑行冒险后能...
    Andy臧阅读 648评论 0 0
  • 像我这样的人,在宁静的夜里,还没入睡的我在细细倾听心底的声音,那是一种呐喊、一种低吼…… 像我这...
    恍生阅读 604评论 2 2
  • 写了个redux实用的例子,顺便用一下webpack做了一些打包工作,没想到折腾了挺久配置,稍微记一下 react...
    色拉油阅读 2,348评论 0 0