[leetcode 222]Count Complete Tree Nodes
2015-09-02 11:20
573 查看
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 2hnodes
inclusive at the last level h.
计算完全二叉树的所有节点的个数。
暴力超时,首先判断该树是否为满完全二叉树,是的话性质求解,否则暴力求解
AC代码:
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 2hnodes
inclusive at the last level h.
计算完全二叉树的所有节点的个数。
暴力超时,首先判断该树是否为满完全二叉树,是的话性质求解,否则暴力求解
AC代码:
class Solution { public: int countNodes(TreeNode* root) { if(root==NULL) return 0; int l=1; int r=1; TreeNode *tempLeft=root; TreeNode *tempRight=root; while(tempLeft) { tempLeft=tempLeft->left; ++l; } while(tempRight) { tempRight=tempRight->right; ++r; } if(l==r) return 1<<l-1; else return countNodes(root->left)+countNodes(root->right)+1; } };
其他Leetcode题目AC代码:https://github.com/PoughER/leetcode
相关文章推荐
- hadoop-2.6.0+zookeper-3.4.6之HA模式两个namenode不同状态active和standby的切换
- node.js 针对不同的请求路径(url) 做出不同的响应
- LeetCode之 Delete Node in a Linked List
- Node.js v0.10.31API手工-DNS
- [Leetcode]#237 Delete Node in a Linked List
- [Leetcode]#24 Swap Nodes in Pairs
- [Leetcode]#19 Remove Nth Node From End of List
- CCFontAtlas,CCGrid,CCGLBufferedNode,CCGrabber解析
- Node js 学习笔记
- jenkins - create node using API(python-jenkins)
- superagent-nodejs处理请求的模块
- 一行命令搞定node.js 版本升级
- leetcode 024 swap nodes in pairs
- easyui+nodejs+sqlserver增删改查实现
- node.js中npm安装的模块在哪个目录下
- NodePad++ 添加NppaStyle.dll问题
- Node.js开发入门—HelloWorld再分析
- [转]七天学会NodeJS
- Windows下Node.js开发入门(1)
- node.js中express的应用