[leetcode] 222.Count Complete Tree Nodes
来源:互联网 发布:淘宝搜索数据查询 编辑:程序博客网 时间:2024/05/16 07:23
题目:
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.
题意:
给定一颗完全二叉树,何谓完全二叉树?即除了最后一层的元素外,其他层元素都是满的,最后一层元素从左到右填充。
现在需要统计这样的完全二叉树有多少个节点。
思路:
考虑这样的树,首先定义求树层的方法,只需要从根节点往左节点一直遍历,直到NULL节点为止即可知高度。
使用递归的方法求最后一层的节点数。如果该节点的右节点的层数等于该节点以下层数减一,说明最后一层的最后一个元素在右子树中。也就是说该节点的左子树的最后一层是满的节点,如果当前节点到叶节点层次是level,那么此时左子树有pow(2, level - 1)个叶子节点。然后递归到右节点上继续求最后一层节点数。
如果该节点的右孩子的层数小于该节点的层数减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; int level = getLevel(root); return getCount(root, level); } int getLevel(TreeNode* root) { int level = -1; while(root != NULL) { level++; root = root->left; } return level; } int getCount(TreeNode* root, int level) { if(level == 0)return 1; int total = pow(2, level); int sum = 0; getLastLevelCount(root, level, total, sum); return (total - 1 + sum); } void getLastLevelCount(TreeNode *node, int level, int total, int &sum) { if(level == 0) { sum += (node == NULL)?0:1; return; } if(getLevel(node->right) == level - 1) { sum += total / 2; getLastLevelCount(node->right, level - 1, total >> 1, sum); } else { getLastLevelCount(node->left, level - 1, total >> 1, sum); } }};
0 0
- [leetcode] 222.Count Complete Tree Nodes
- [leetcode] 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes LeetCode
- leetcode 222. Count Complete Tree Nodes
- LeetCode *** 222. Count Complete Tree Nodes
- LeetCode 222. Count Complete Tree Nodes
- leetcode.222. Count Complete Tree Nodes
- [leetcode]222. Count Complete Tree Nodes
- [leetcode] 222. Count Complete Tree Nodes
- 222. Count Complete Tree Nodes(leetcode) 超时
- [LeetCode]222. Count Complete Tree Nodes
- (未完成!)Leetcode 222. Count Complete Tree Nodes
- LeetCode 222. Count Complete Tree Nodes
- [LeetCode]222. Count Complete Tree Nodes
- [leetcode]222. Count Complete Tree Nodes
- leetcode 222. Count Complete Tree Nodes
- leetcode 222. Count Complete Tree Nodes
- [LeetCode] Count Complete Tree Nodes
- 虚幻引擎中的数组---TArray: Arrays
- Html-基础知识
- SqliteDatabase之SqliteOpenHelper_封装方法
- iOS笔记-(利用EGORefreshTableHeaderView自定义上拉加载和下拉刷新)
- 基于规则引擎的电信CRM系统架构研究
- [leetcode] 222.Count Complete Tree Nodes
- Intent用法实例
- UE4编码规范
- SqliteDatabase之如何读取数据库()
- 双链表实例
- 组合查询 ——vb
- Java接口
- hihocoder——1041国庆出游(搜索)
- 单链表排序(插入与归并)