练习题 (八)
2015-07-02 20:48
316 查看
题目:
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,(错误)
解答,正确:
把上面的中间代码的反注释掉,运行通过。
心得:
这个题目,需要利用到满二叉树的节点数为2的N次方减1,并且我们做题目的时候,通常做出来的是前面一种解答的形式。
这个题目,混搭了满二叉树的求节点数,和完全二叉树的性质。当然,我也只做到了前面一种解答,测试代码报告效率不高,时间已经超过了最大时间。后面再补上了中间的代码。
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,并且我们做题目的时候,通常做出来的是前面一种解答的形式。
这个题目,混搭了满二叉树的求节点数,和完全二叉树的性质。当然,我也只做到了前面一种解答,测试代码报告效率不高,时间已经超过了最大时间。后面再补上了中间的代码。
相关文章推荐
- resin安装配置
- Android初学之------检查前置摄像头是否存在
- 解决ACM异常wt.fc.ObjectNoLongerExistsException
- Java程序设计第十七周之图片的随机显示部分实现
- STM32W108无线ZigBee射频芯片引脚说明(下篇)
- 推荐使用Numba加速Python科学计算
- 发下牢骚(一)
- Hadoop入门系列(3) -- Eclipse+Hadoop开发环境搭建
- Java程序员应该知道的10个eclipse调试技巧
- Android开发常见问题之Handler引起的内存泄漏
- Nexus搭建Maven私服
- Dubbo 架构分析
- 2015华为软赛(四)——数据结构设计
- 从尾到头打印链表
- 大话设计の创建模式
- 【Linear Support Vector Machine】林轩田机器学习技法
- gulp系列文章一 fis vs grunt vs gulp,为什么要是gulp呢?
- Android Service解析
- hdu 4169 二分匹配最大独立集 ***
- IOS中定时器NSTimer的开启与关闭