Count Complete Tree Nodes - LeetCode 222

题目描述:
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.

Hide Tags Tree Binary Search

分析:
由于是二叉搜索树,那么就满足完全二叉树的结构。只有可能最后一层的右边会少几个结点。
因此,如果是满二叉树的话,只需要求出整颗二叉搜索树的层数h,然后利用满二叉树的性质:节点数为2^h-1。
否则就只有分别求出左子树的结点数与右子树的结点数之和了。求这两个字数的结点数的方法和判断根节点一样,也是先判断是否是满二叉树,即递归调用即可。

以下是C++实习代码:

/**//84ms*/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int lef_height(TreeNode* root){ //求出左子树的最大层次
        int cnt = 0;
        while(root != NULL){
            cnt++;
            root = root->left;
        }
        return cnt;    
    }
    int rig_height(TreeNode* root){ //求出右子树的最大层次
        int cnt = 0;
        while(root != NULL){
            cnt++;
            root = root->right;
        }
        return cnt;    
    }
    
    int countNodes(TreeNode* root) {
        int cnt = 0;
        if(root == NULL)
            return cnt;
        int lef = lef_height(root);
        int rig = rig_height(root);
        if(lef == rig) //左右子树的层次是相等的,说明是满二叉树,直接用公式计算节点总数
            return (1<<lef)-1;
        else //不是满二叉数,那么递归调用计算出左右字数的结点数再加上根节点数即可
            return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值