[leetcode][tree] Count Complete Tree Nodes
2015-06-07 17:19
627 查看
题目:
Given a complete binary
tree, count the number of nodes.
Given a complete binary
tree, count the number of nodes.
/** * 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(NULL == root) return 0; TreeNode *p = root->left; int leftHeight = 0, rightHeight = 0; //求得左子树的高度 while(p != NULL){ p = p->left; ++leftHeight; } //求得右子树的高度 p = root->right; while(p != NULL){ p = p->right; ++rightHeight; } //如果两者等高,则说明是满二叉树,直接计算得到节点个数 if(leftHeight == rightHeight){//满二叉树 return (1 << (leftHeight+1))-1; } //如果两者不等高,递归求得左右子树的节点个数,当前树的节点个数等于左右子树节点个数之和加1(根节点) return 1 + countNodes(root->left) + countNodes(root->right); } };
相关文章推荐
- inode理解
- 磁盘inode不足,使用xfs文件系统
- LeetCode Count Complete Tree Nodes
- leetcode[19]:Remove Nth Node From End of List Total
- node.js中关于使用formidable模块实现文件上传至指定目录的问题
- NodeJS中的NPM代理设置
- [LeetCode][JavaScript]Count Complete Tree Nodes
- Count Complete Tree Nodes
- nodejs版本更新问题:express不是内部或外部命令
- nodejs版本更新问题:express不是内部或外部命令
- LeetCode Count Complete Tree Nodes
- nodejs express 安装需要注意的一些问题
- [LeetCode]Count Complete Tree Nodes
- Leetcode: Count Complete Tree Nodes
- DaoCloud部署Node
- 10个令人惊讶的NodeJS开源项目
- leetcode - Count Complete Tree Nodes
- openstack-计算节点安装(Node)
- [LeetCode] Count Complete Tree Nodes
- Count Complete Tree Nodes