1,问题简述
给出一个完全二叉树,求出该树的节点个数。
2,示例
代码语言:javascript复制说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/
2 3
/ /
4 5 6
输出: 6
3,题解思路
队列的使用
4,题解程序
代码语言:javascript复制
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class CountNodesTest {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t3.left = t6;
int countNodes = countNodes(t1);
System.out.println("countNodes = " countNodes);
int count = countNodes2(t1);
System.out.println("count = " count);
}
public static int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.add(root);
List<Integer> list = new ArrayList<>();
while (!deque.isEmpty()) {
int size = deque.size();
for (int i = 0; i < size; i ) {
TreeNode node = deque.poll();
list.add(node.val);
if (node.left != null) {
deque.add(node.left);
}
if (node.right != null) {
deque.add(node.right);
}
}
}
return list.size();
}
public static int countNodes2(TreeNode root) {
if (root == null) {
return 0;
}
int leftLevel = countLevel(root.left);
int rightLevel = countLevel(root.right);
if (leftLevel == rightLevel) {
return countNodes(root.right) (1 << leftLevel);
} else {
return countNodes(root.left) (1 << rightLevel);
}
}
private static int countLevel(TreeNode root) {
int level = 0;
while (root != null) {
level ;
root = root.left;
}
return level;
}
}
5,题解程序图片版
6,总结
队列的特点就是先进先出