码迷,mamicode.com
首页 > 其他好文 > 详细

练习题 (八)

时间:2015-07-02 22:25:05      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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,(错误)

/**
 * 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 countNodes(TreeNode* root) {
        if(root == NULL)
            return 0;

        // int leftHeight = 0;
        // int rightHeight = 0;

        // TreeNode *pLeft = root;
        // while(pLeft) {
        //     ++leftHeight;
        //     pLeft = pLeft->left;
        // }

        // TreeNode *pRight = root;
        // while(pRight) {
        //     ++rightHeight;
        //     pRight = pRight->right;
        // }

        // if(leftHeight == rightHeight)
        //     return pow(2, leftHeight)-1;

        return countNodes(root->left) + countNodes(root->right) + 1;

    }
};

解答,正确:

把上面的中间代码的反注释掉,运行通过。

心得:

这个题目,需要利用到满二叉树的节点数为2的N次方减1,并且我们做题目的时候,通常做出来的是前面一种解答的形式。

这个题目,混搭了满二叉树的求节点数,和完全二叉树的性质。当然,我也只做到了前面一种解答,测试代码报告效率不高,时间已经超过了最大时间。后面再补上了中间的代码。

练习题 (八)

标签:

原文地址:http://www.cnblogs.com/ender-cd/p/4617126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!