Count Complete Tree Nodes 统计完全二叉树的节点数
2015-06-12 20:11
706 查看
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.
/** * 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) { return solve(root); } int solve(TreeNode *root) { if(root == NULL) return 0; int left=solve(root->left); int right=solve(root->right); return left+right+1; } */ int countNodes(TreeNode* root) { if(root==NULL) return 0; int numL=0,numR=0; TreeNode *lt=root; TreeNode *rt=root; while(lt!=NULL) { numL++; lt=lt->left; } while(rt!=NULL) { numR++; rt=rt->right; } if(numL==numR) return pow(2,numL)-1; else return countNodes(root->left)+countNodes(root->right)+1; } };
相关文章推荐
- nodejs之child_process子进程模块
- Populating Next Right Pointers in Each Node
- net_kernel:monitor_nodes 订阅node连接\断开消息
- 详细讲解nodejs中使用socket的私聊的方式
- 【node.js】基础<一>
- nodejs之connect模块
- Node开发这块目前比较理想的装配建议
- 使用node.js express 4.x 模块 搭建angular.js开发环境
- #leetcode#Populating Next Right Pointers in Each Node
- node-webkit实践-一键安装
- Windows下nodejs的安装与简单事例
- 编译contrail-nodemgr
- nodejs 文件与文件操作(读写文件 删除 重命名)
- 收集了NodeJS开发中常用的一些模块。
- Nodejs异步回调的优雅处理方法
- 通过Anuglar Material串串学客户端开发 - NodeJS模块机制之Module.Exports
- [6]_先从前端说起 - Nodejs学习之基础(1)
- 模拟namenode崩溃,使用secondarynamenode恢复
- leetcode 019 Remove Nth Node From End of List (Python)
- HDFS-datanode数据块部分笔记