解法:使用按層遍歷二叉樹的非遞歸形式
每次到達此層末尾時就打印。
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());
}
}
}
}
總結:按層遍歷二叉樹的變形。