LeetCode173-二叉搜索树迭代器

题目链接

英文链接:https://leetcode.com/problems/count-complete-tree-nodes/

中文链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/

题目详述

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例:

1
2
3
4
5
6
7
8
输入: 
1
/ \
2 3
/ \ /
4 5 6

输出: 6

题目详解

求一棵树的结点个数的通用代码如下(时间复杂度为 O(n)):

1
2
3
4
5
6
public class LeetCode_00222 {

public int countNodes(TreeNode root) {
return root == null ? 0 : 1 + countNodes(root.left) + countNodes(root.right);
}
}
  • 由于题目限定给定的数为完全二叉树,可能存在左子树为满二叉树的情况,这一部分可以直接根据深度计算出结点个数,不满足的地方仍旧需要遍历。
  • 相当于二分查找最后一层最后一个结点的位置,查找的复杂度为 O(logn),最多查找 O(logn) 次,所以时间复杂度为 O(logn * logn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LeetCode_00222 {

public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = 0, rightDepth = 0;
for (TreeNode node = root; node != null; node = node.left) {
++leftDepth;
}
for (TreeNode node = root; node != null; node = node.right) {
++rightDepth;
}
if (leftDepth == rightDepth) {
return (1 << leftDepth) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}