练习题 (八)

题目:

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,并且我们做题目的时候,通常做出来的是前面一种解答的形式。

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

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