Q222:满二叉树结点个数

/**
 * 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 h = getLevel(root,1);
        return so(root,1,h);
    }
    
    
    /*
        
    */
    public int so(TreeNode root,int h,int sumh){
        if(h==sumh){
            return 1;
        }
        //当当前节点的右子树的深度==sumh,说明左子树是满二叉树,则可以根据公式求出左子树个数2^(maxh-h)-1 再加上父节点
        //+1 = 2^(maxh-h),然后对右子树递归求解
        
        //否则
        //当当前节点的右子树的深度==sumh-1,说明右子树是满二叉树,则可以根据公式求出左子树个数2^(maxh-h-1)-1 再加上父节点
        //+1 = 2^(maxh-h-1),然后对左子树递归求解         
        if(getLevel(root.right,h+1)==sumh){
           
            return (1<<(sumh-h)) + so(root.right,h+1,sumh);
        }else{
            
            return (1 << (sumh-h-1)) + so(root.left,h+1,sumh);
        }
    }
//     求当前字数的最大层数
    public int getLevel(TreeNode node,int h){
        int count=h;
        while(node!=null){
            count++;
            node = node.left;
        }
        return count-1;
    }
    
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值