大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/count-complete-tree-nodes/description/
内容
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, 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.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
- The number of nodes in the tree is in the range [0, 5 * 104].
- 0 <= Node.val <= 5 * 104
- The tree is guaranteed to be complete.
解题
这题就是要求一个完全二叉树的节点个数。解这题需要知道完全二叉树的概念:
一棵深度为k的有n个结点的二叉树,对树中的结点按从上至下、从左到右的顺序进行编号,如果编号为i(1≤i≤n)的结点与满二叉树中编号为i的结点在二叉树中的位置相同,则这棵二叉树称为完全二叉树。
完全二叉树是由满二叉树发展而来。满二叉树的定义是:
除最后一层无任何子节点外,每一层上的所有结点都有两个子结点的二叉树。
上图就是满二叉树。但是下图不是满二叉树,它是完全二叉树
假设完全二叉树是h深度,则其h-1深度层是满二叉树。h层元素全部靠左侧分布,即不存在“只有右节点,而无左节点”的情况。比如下图就不是全完二叉树
我们的解题思路就是:先找到满二叉树层的深度(不停遍历右子树),然后统计最后一层叶子节点数(先序遍历)。如果最后一层出现空子树,则停止遍历。
struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode() : val(0), left(nullptr), right(nullptr) {}TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};class Solution {
public:int countNodes(TreeNode* root) {int fullRightDepth = 0;TreeNode* cur = root;while (cur != nullptr) {fullRightDepth++;cur = cur->right;}int count = 0;countLastLevel(root, 1, fullRightDepth, count);return (1 << fullRightDepth) - 1 + count;}private:bool countLastLevel(TreeNode* root, int depth, int fullRightDepth, int& count) {if (root == nullptr) {return false;}if (depth == fullRightDepth) {if (root->left != nullptr) {count++;}if (root->right != nullptr) {count++;}if (root->left == nullptr && root->right == nullptr) {return false;}return true;} else {if ( 0 == countLastLevel(root->left, depth + 1, fullRightDepth, count)|| 0 == countLastLevel(root->right, depth + 1, fullRightDepth, count)) {return false;}return true;}}
};
代码地址
https://github.com/f304646673/leetcode/blob/main/222-Count-Complete-Tree-Nodes/cplusplus/src/solution.hpp