zoukankan      html  css  js  c++  java
  • 练习题 (八)

    题目:

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

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

  • 相关阅读:
    蓝书3.6 割点与桥
    蓝书3.5 强连通分量
    蓝书3.4 差分约束系统
    蓝书3.3 SPFA算法的优化
    蓝书3.2 最短路
    蓝书3.1 最小生成树
    luogu 4630 [APIO2018] Duathlon 铁人两项
    Codeforces Round #124 (Div. 1) C. Paint Tree(极角排序)
    dutacm.club Water Problem(矩阵快速幂)
    dutacm.club 1094: 等差区间(RMQ区间最大、最小值,区间GCD)
  • 原文地址:https://www.cnblogs.com/ender-cd/p/4617126.html
Copyright © 2011-2022 走看看