打印二叉树的所有最右节点

解法:使用按层遍历二叉树的非递归形式
每次到达此层末尾时就打印。

public class PrintTreeRightNode {
public static class Node{
private Node left;
private Node right;
private int value;
public Node(int value){
this.value = value;
}
}
//按层遍历使用队列。
public void printTreeRightNode(Node head){
if(head==null){
return ;
}
Queue<Node> queue = new ArrayDeque<>();
queue.add(head);
int start = 0;//设置一层的开始位置
int end = 1; //设置一层的结束位置
while (!queue.isEmpty()){
Node node = queue.poll();
start++;
if(node.left!=null){ //添加左孩子
queue.add(node.left);
}
if(node.right!=null){ //添加右孩子
queue.add(node.right);
}
if(start==end){ //当到达末尾时
start = 0;
end = queue.size();//这层完事时,因为存的都是下一层的孩子,所以队列的大小就是孩子的个数。
System.out.print(queue.peek());
}
}
}
}
总结:按层遍历二叉树的变形。

猜你喜欢

转载自www.cnblogs.com/liuwentao/p/9484569.html