leetcode.222. Count Complete Tree Nodes
2016-05-10 21:08
274 查看
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.
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.
/** * 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 l = getLeft(root) ; int r = getRight(root) ; if(l==r) { return (2<<l) - 1; } else { return countNodes(root->left) + countNodes(root->right) + 1; } } int getLeft(TreeNode* root) { int count = 0; while(root->left!=NULL) { root = root->left; ++count; } return count; } int getRight(TreeNode* root) { int count = 0; while(root->right!=NULL) { root = root->right; ++count; } return count; } };
相关文章推荐
- 第一个Node.js应用
- Node.js的安装
- 今天使用babel遇到的一个错误
- 云监控中inode使用率监控具体作用是什么
- Nodejs 安装
- Node.js学习总纲
- hadoop关不掉namenode的解决办法
- nodejs学习之表单提交(1)
- 237DeleteNodeinaLinkedList
- 《深入浅出Node.js》学习笔记——(二)模块机制
- Leetcode - 19. Remove Nth Node from end of List
- nodemailer发送邮件遇到的一些问题
- leetcode 19. Remove Nth Node From End of List
- 删除 Nodejs的方法,记录一下
- node短信接口开发
- hadoop datanode重启出现namenode的clusterID和datanode的不一致。
- ReactNative NodeJs v5.7.0稳定版官方下载
- node.js常用方法
- Nodejs 与MySQL交互(felixge/node-mysql)
- 求教——使用node做表单,刷新浏览器页面,浏览器为什么会重复提交上次所填的信息