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

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

  • 相关阅读:
    四则运算出题系统,java
    Javaweb测试
    《构建之法》 读书笔记(6)
    使用ProcDump在程序没有响应时自动收集dump
    NASA关于如何写出安全代码的10条军规
    C#和C++中的float类型
    避免在C#中使用析构函数Finalizer
    C#性能优化的一些技巧
    从bug中学习怎么写代码
    Code Smell那么多,应该先改哪一个?
  • 原文地址:https://www.cnblogs.com/ender-cd/p/4617126.html
Copyright © 2011-2022 走看看