222. Count Complete Tree Nodes
来源:互联网 发布:计算机专业不想编程 编辑:程序博客网 时间:2024/05/22 13:30
Given a complete binary 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; }};
0 0
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes**
- 222. Count Complete Tree Nodes
- 1013 Problem M
- sqlalchemy 使用不同文件中的数据模型
- python(二)列表,元组,循环
- 爬虫技术入门(一)
- ICS 家庭作业2.65
- 222. Count Complete Tree Nodes
- 【BZOJ4319】cerc2008 Suffix reconstruction【构造】【后缀数组】
- PostgreSQL
- HTTP Content-type 对照表___http://tools.jb51.net/table/http_content_type
- 查询数据库中为null字段的数据
- java中多线程介绍
- 网络编程知识(11)--DNS
- get请求中文乱码
- hdu1111 Secret Code ----复数+DFS