222. Count Complete Tree Nodes

Description

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.

Solution

Recursive

注意一定要仔细理解complete tree。对于每层来说,要么是满的,要么是连续的。

从root开始,分别沿着最左边和最右边计算高度,如果高度相同,则证明树是完全填满的,node数量直接根据height计算出;若高度不同,则递归调用。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftHeight = height(root, true);
        if (height(root, false) == leftHeight) {
            // must use bit manipulation, otherwise it will TLE
            return (1 << leftHeight) - 1;   
        }
        
        return 1 + countNodes(root.left) + countNodes(root.right);
    }
    
    public int height(TreeNode root, boolean isLeft) {
        int height = 0;
        
        while (root != null) {
            ++height;
            root = isLeft ? root.left : root.right;
        }
        
        return height;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,173评论 0 10
  • 三月生机勃勃,也是让酝酿多时的2017新年计划真正实施的好日子。春节在拉萨度过的最后一晚,建立了自己第一个微...
    CY_beijing阅读 1,562评论 0 0
  • (作为一个语文的渣渣,大家不要去找病句什么的……) 说到性格这种东西,我觉得我应该大概也许也算是外向的人吧,虽然有...
    马斯特奶酪阅读 1,652评论 0 2
  • 酒是粮食精,越喝越精神!
    从头越_459a阅读 2,976评论 0 0
  • 1.童年的我看待疾病:疾病和愁眉苦脸、脾气暴躁、阴暗,相联系。爸爸身体不好,整个家庭都很不安。妈妈总说,爸爸身体不...
    拥抱小小的我阅读 3,339评论 0 0

友情链接更多精彩内容