来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/
描述
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
题解
递归版
/**
* 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 1 + countNodes(root.left) + countNodes(root.right);
}
}
复杂度分析
- 时间复杂度:
- 空间复杂度:
=
,其中d指的是树的的高度,运行过程中堆栈所使用的空间。
迭代版
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int computeDepth(TreeNode node) {
int d = 0;
while (node.left != null) {
node = node.left;
++d;
}
return d;
}
public boolean exists(int idx, int d, TreeNode node) {
int left = 0, right = (int) Math.pow(2, d) - 1;
int pivot;
for (int i = 0; i < d; i++) {
pivot = left + (right - left) / 2;
if (idx <= pivot) {
node = node.left;
right = pivot;
} else {
node = node.right;
left = pivot + 1;
}
}
return node != null;
}
public int countNodes(TreeNode root) {
if (null == root) {
return 0;
}
int d = computeDepth(root);
if (0 == d) {
return 1;
}
int left = 1, right = (int)Math.pow(2, d) - 1;
int pivot;
while (left <= right) {
pivot = left + (right - left) / 2;
if (exists(pivot, d, root)) {
left = pivot + 1;
} else {
right = pivot - 1;
}
}
return (int)Math.pow(2, d) - 1 + left;
}
}
复杂度分析
- 时间复杂度:
=
,其中d是树的高度;
- 空间复杂度:
;