Count Complete Tree Nodes
来源:互联网 发布:北京人口密度数据 编辑:程序博客网 时间:2024/05/23 01:35
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.
采用二分法去做,首先 从根节点考虑,若最左边的高度和最右边的相等,我们就知道我们可以返回了。若不想等,我们需要确认左子树和右子树哪个节点中包含不完整的节点,换句话说,需要知道,最后一层,从左往右,叶子节点有几个(考虑最后一层不完整的情况)。
那么怎么确定是左子树还是右子树不完整呢,我们需要判断左子树中的右子树的最右深度(left->right),然后呢 如果和左子树的最左子树深度一致,那么我们要递归找右子树了。此时的最后一层的叶子的数目是需要累加的。这里还有一个问题,当右子树的最左子树的深度等于右子树的最右子树的深度时 ,实际上我们已经不再需要遍历了,因为此时可以判定左子树中的叶子节点比右子树中的叶子节点多一。
class Solution {public: int depthl(TreeNode* node){ int depth=0; while(node){ node=node->left; depth++; } return depth; } int depthr(TreeNode* node){ int depth=0; while(node){ node=node->right; depth++; } return depth; } int countNodes(TreeNode* root) { TreeNode* node=root; int maxdepth=depthl(root); int curlen=maxdepth-1; int index=0; if(!root)return 0; int d1,d2; TreeNode *left,*right; d1=depthl(node->left); d2=depthr(node->right); if(d1==d2) return pow(2,maxdepth)-1; while(node){ curlen--; left=node->left; right=node->right; if(!left) return pow(2,maxdepth-1)+index-1; if(!right) return pow(2,maxdepth-1)+index; //d1=depthTree(left->left); d1=depthr(left->right); if(d1==curlen){ index+=pow(2,curlen); d1=depthl(right->left); if(d1==curlen-1){ return pow(2,maxdepth-1)+index-1; } else{ node=right; } } else{ // index+=pow(2,curlen-1); node=left; } } return pow(2,maxdepth-1)+index-1; }};
0 0
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes(****)
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- Count Complete Tree Nodes
- VS2008/VS2012/MFC/C++/ACCESS/Redistributable Package/installshield/打包/安装/部署
- ACdream 1099 - 瑶瑶的第K大
- 大端与小端
- 手写全排列(递归 | 非递归)
- 十三周项目三
- Count Complete Tree Nodes
- YT03-递推求解课堂题目-1001 蟠桃记-(6.7日-烟台大学ACM预备队解题报告)
- Android开发环境搭建
- Linux下TFTP与NFS服务器配置
- 十四周项目一
- 关于身份认证中的Authenticator及AuthenticationStrategy
- YT03-递推求解课堂题目-1002 折线分割平面-(6.7日-烟台大学ACM预备队解题报告)
- MapReduce之Combiner组件
- C++学习笔记之---namespace的使用