一:求二叉树的宽度,打印二叉树最左侧节点,最右侧节点
/**
* 层序遍历+输出最左节点+求最宽度
* @param root
* @return
*/
public static int getMaxWidth(BinaryTreeNode root) {
Queue<BinaryTreeNode> queue = new LinkedList<>();
if (root == null)
return 0;
int maxWidth = 1;
int size = 1;
queue.offer(root);
while (!queue.isEmpty()) {
for (int i = 0; i < size; i++) { //遍历每一层
BinaryTreeNode node = queue.poll();
if (i==0) {
System.out.println(node.getData());
}
if (node.getLeft()!=null) {
queue.offer(node.getLeft());
}
if (node.getRight()!=null) {
queue.offer(node.getRight());
}
}
size = queue.size();//得到下一层的宽度
maxWidth=Math.max(maxWidth, size);
}
return maxWidth;
}