【LeetCode】222. Count Complete Tree Nodes
2015-07-09 17:48
519 查看
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.
完全二叉树相比普通二叉树,在计数时候一个trick在于,当最后一层是满的(最左深度等于最右深度),
就不需要通过遍历方式来计数,直接等于2^h - 1
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.
完全二叉树相比普通二叉树,在计数时候一个trick在于,当最后一层是满的(最左深度等于最右深度),
就不需要通过遍历方式来计数,直接等于2^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; TreeNode* l = root; int lefth = 0; while(l->left) { lefth ++; l = l->left; } TreeNode* r = root; int righth = 0; while(r->right) { righth ++; r = r->right; } if(lefth == righth) return pow(2.0, lefth+1) - 1; else return 1 + countNodes(root->left) + countNodes(root->right); } };
相关文章推荐
- 【LeetCode 222_完全二叉树_遍历】Count Complete Tree Nodes
- leetcode 019 —— Remove Nth Node From End of List
- nodejs对文件进行分页
- node.js+express,实现RESTful API
- Node.js 入门
- node.js通过edge访问.net动态链接库
- LeetCode——Count Complete Tree Nodes
- ubuntu / Ubuntu Kylin下安装和卸载 Nodepadqq
- Django:ExtendsNode: extends 'base/base.html'> must be the first tag in the template.
- Populating Next Right Pointers in Each Node
- Innode表空间碎片优化
- Swap Nodes in Pairs
- node js 打包文件
- MAC下安装node.js
- 动手编写Node的C++模块
- Reverse Nodes in k-Group
- Hbase出现ERROR: Can't get master address from ZooKeeper; znode data == null解决办法
- [leedcode 25] Reverse Nodes in k-Group
- 24. Swap Nodes in Pairs
- 用C++为nodejs 写组件,提高node处理效率