Count Complete Tree Nodes
2015-07-23 12:34
513 查看
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.
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.
/** * 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* tmp=root->left; int leftheight=1; int rightheight=1; while(tmp!=NULL) { tmp=tmp->left; leftheight++; } tmp=root->right; while(tmp!=NULL) { tmp=tmp->right; rightheight++; } if(leftheight==rightheight) { return (1<<leftheight)-1; } else return countNodes(root->left)+countNodes(root->right)+1; } };
相关文章推荐
- Delete Node in a Linked List
- LeetCode #19 Remove Nth Node From End of List
- Populating Next Right Pointers in Each Node
- nodejs之获取客户端真实的ip地址+动态页面中引用静态路径下的文件及图片等内容
- [Leetcode] Swap Nodes in Pairs
- NodeJS优缺点及适用场景讨论
- XmlNode中的Value值为空的问题
- [Leetcode 24, Medium] Swap Nodes in Pairs
- [Leetcode 117, Hard] Populating Next Right Pointers in Each Node II
- [Leetcode 116, Medium] Populating Next Right Pointers in Each Node
- [leedcode 117] Populating Next Right Pointers in Each Node II
- Remove Nth Node From End of List
- [leedcode 116] Populating Next Right Pointers in Each Node
- NodeJS开发者-资质分级评判标准
- Populating Next Right Pointers in Each Node II
- HTML DOM nodeName nodeValue
- [leetcode] Reverse Nodes in k-Group
- 使用Node.js+Socket.IO搭建WebSocket实时应用(聊天室)
- node.js 入门示例
- NodeJS中的事件