222. Count Complete Tree Nodes
2016-05-11 15:58
435 查看
Given a complete binary
tree, count the number of nodes.
计算完全二叉树的节点数目。满二叉树的节点数是2^h-1, h为树的高度。
tree, count the number of nodes.
计算完全二叉树的节点数目。满二叉树的节点数是2^h-1, 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) { /*------递归算法超时 if(root==NULL) return 0; int count = 1; count += countNodes(root->left); count += countNodes(root->right); return count; -------------------*/ if(root==NULL) return 0; int leftH = getLeftHeight(root); int rightH = getRightHeight(root); if(leftH==rightH) return (1<<leftH)-1; else { return countNodes(root->left) + countNodes(root->right)+1; } } int getLeftHeight(TreeNode* root) { if(root==NULL) return 0; int h = 1; while(root->left) { h++; root= root->left; } return h; } int getRightHeight(TreeNode* root) { if(root==NULL) return 0; int h = 1; while(root->right) { h++; root= root->right; } return h; } };
相关文章推荐
- #24 Swap Nodes in Pairs
- 【Leetcode】:116. Populating Next Right Pointers in Each Node 问题 in JAVA
- xpath与nodejs解析xml
- nodejs xpath
- Jenkins Slave Nodes – using the Swarm Plugin
- HADOOP 启动NodeManager闪退,logs信息:java.net.NoRouteToHostException: 没有到主机的路由
- [NodeJS]Jenkins-cli
- Hadoop2源码分析-HDFS datanode核心模块分析
- Node.js机制及原理理解初步
- LeetCode 025 Reverse Nodes in k-Group
- 树——populating-next-right-pointers-in-each-node(层序遍历变型)
- leetcode.222. Count Complete Tree Nodes
- 第一个Node.js应用
- Node.js的安装
- 今天使用babel遇到的一个错误
- 云监控中inode使用率监控具体作用是什么
- Nodejs 安装
- Node.js学习总纲
- hadoop关不掉namenode的解决办法
- nodejs学习之表单提交(1)