leetcode--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.


题意:给定一棵完全二叉树,计算节点数目。

分类:二叉树


解法1:完全二叉树的定义是,除最后一层外,每一层上的节点数均达到最大值;在最后一层上只缺少右边的若干结点。

完全二叉树的一个特殊例子是满二叉树。

如果一棵树是满二叉树,那么我们可以用公式2^k-1计算它的节点数目。

如果不是满二叉树,我们要分别计算左子树和右子树,这是一个递归过程,最好左右子树和+1,为结果

根据上面的说法,我们可以先通过查找最左边节点的个数,最右边节点的个数

如果这两个数目相同,就是满二叉树,可以通过公式直接返回

如果不同,则递归分别计算左右子树的数目

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
        if(root==null) return 0;
        int left = getLeft(root.left)+1;
        int right = getRight(root.right)+1;
        if(left==right){//如果左右相等,就是满二叉树
            return (2<<(left-1))-1;  
        }else{//如果左右不等,分别递归计算
            return countNodes(root.left)+countNodes(root.right)+1;
        }
    }
    
    /**
     * 获得最左边节点的数目 
     */
    int getLeft(TreeNode root){
        int left = 0;
        while(root!=null){
            left++;
            root = root.left;
        }
        return left;
    }
    
    /**
     * 获得最右边节点的数目
    int getRight(TreeNode root){
        int right = 0;
        while(root!=null){
            right++;
            root = root.right;
        }
        return right;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值