You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a complete binary tree, count the number of nodes.
Note:
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.
class Solution {
int num = 0;
public int countNodes(TreeNode root) {
preOrder(root);
return num;
}
void preOrder(TreeNode node) {
if (node == null) return;
++num;
preOrder(node.left);
preOrder(node.right);
}
}
Given a complete binary tree, count the number of nodes.
Note:
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.
Example:
这道题求的是完全二叉树的节点数。
最简单的方法是直接用先序遍历,遍历所有的节点,这样的时间复杂度是O(n)(n是节点个数),但甚至可以用一行代码来解决:
显然上述方法没有利用到完全二叉树的特性,其不可能出现一个只有右孩子而没有左孩子的节点。完全二叉树可以看成是一部分满二叉树加上最后一层叶子节点构成。所以我们可以分两部分求解。先求得二叉树的层数,然后求得满二叉树的节点数是2的层数幂次方减去一
(int)Math.pow(2, layerNum - 1) - 1
;接着去求最后一层节点数,每层递归,如果当前层数不是最后一层,返回0,否则返回1,最后回溯的结果就是最后一层节点数。这个方法时间复杂度大概是O(l + m),l是树的深度,m是最后一层节点数。还有一种方法同样递归求解,同样每层递归,如果当前层是满二叉树,调用_(1 << height) - 1_,否则继续往下一层。
参考资料:
The text was updated successfully, but these errors were encountered: