222.leetcode.Count Complete Tree Nodes(medium)[完全二叉树 节点个数]

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.

题目中完全二叉树的最大的节点是满二叉树的时候为2^h-1(h为高度,根节点为1)。采用暴力破解对整棵树遍历一遍会超时,最后利用完全二叉树的特点,首先遍历左子树的左子树得到这棵树的左子树最大高度,同理找到右子树的右子树的最大高度,如果两者相等那么说明是一棵满二叉树可以直接得到答案。否则的话把问题分而治之,那么对左右子树分别求节点数再加上根节点的节点个数1.

/**
 * 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:
    //计算完全二叉树的节点数,下面是暴力破解的方式,遍历一遍整棵树
    /*void countNodes(TreeNode* root,int &n)
    {
        if(root != NULL) ++n;
        else return;
        countNodes(root->left,n);
        countNodes(root->right,n);
        return;
    }
    int countNodes(TreeNode* root) {
        if(root == NULL) return 0;
        int n = 0;
        countNodes(root,n);
        return n;
    }*/
    int getHeight1(TreeNode *root)
    {
        if(root == NULL) return 0;
        int n = 1;
        while(root->left != NULL){ n++; root = root->left;}
        return n;
    }
    int getHeight2(TreeNode *root)
    {
        if(root == NULL) return 0;
        int n = 1;
        while(root->right != NULL){ n++; root = root->right;}
        return n;
    }
    int countNodes(TreeNode* root) {
        if(root == NULL) return 0;
        int lheight = getHeight1(root->left);
        int rheight = getHeight2(root->right);
        if(lheight == rheight) 
            return pow(2,1+lheight)-1;
        else
            return countNodes(root->left)+countNodes(root->right)+1;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值