题目
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
解法一:全部遍历
直接遍历即可。
注意:没用到完全二叉树这个条件,因而不是很好的解。
如果这样做,那这题可看作简单难度。做了对自身也不会有什么提高。
时间复杂度:O(n)
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
结果
解法二:二分
满树计算公式:2^h - 1
获取左右子树的深度。左子树深度 hl ,右子树深度 hr。
有以下两种可能:
- hl == hr:左子树为满树,直接计算左子树的节点数,然后继续递归右子树。
- hl > hr:右子树为满树(相比左子树少了一层),直接计算右子树的节点数,然后继续递归左子树。
时间复杂度:O(h^2) (h 是树的高度)
(小提示:下述代码还可以更优!若整棵树就是满树,当 hl == hr 时,能不能尝试提前结束递归呢?请自行优化。)
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int hl = depth(root.left);
int hr = depth(root.right);
if(hl == hr) {
return 1 + (1 << hl) - 1 + countNodes(root.right);
} else {
return 1 + (1 << hr) - 1 + countNodes(root.left);
}
}
private int depth(TreeNode node) {
int d = 0;
while(node != null) {
node = node.left;
d ++;
}
return d;
}
}