码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-16 00:49:57      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:++   设置   ret   int   int end   poll   变形   void   his   

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

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());
}
}
}
}
总结:按层遍历二叉树的变形。

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

标签:++   设置   ret   int   int end   poll   变形   void   his   

原文地址:https://www.cnblogs.com/liuwentao/p/9484569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!