java算法(一)二叉树逐层遍历打印(分层换行)

思路是维护一个节点队列和两个节点引用last(上一行最后的元素).nlast(本行最后的元素),初始化时nlast=last=root。不断取出队列第一个元素x,然后将x的左右孩子入队并移动nlast到最后一个孩子。然后判断x是否是last,是则打印并换行并将last指向nlast(开始下一行),否则普通打印。     文字描述不太清晰,结合程序走一遍就理解了。

package structure;

import java.util.LinkedList;

public class BinaryTreeNode {
	
	private int value;
	private BinaryTreeNode leftChild;
	private BinaryTreeNode rightChild;
	

	public void print(){
		LinkedList<BinaryTreeNode> queue=new LinkedList<>();
		queue.add(this);
		BinaryTreeNode last=this;
		BinaryTreeNode nlast=this;
		while(!queue.isEmpty()){
			BinaryTreeNode node=queue.poll();
			if(node.getLeftChild()!=null){
				queue.offer(node.getLeftChild());
				nlast=queue.getLast();
			}
			if(node.getRightChild()!=null){
				queue.offer(node.getRightChild());
				nlast=queue.getLast();
			}
			if (node==last) {
				System.out.print(node.getValue()+"\n");
				last=nlast;
			} else {
				System.out.print(node.getValue()+" ");
			}
		}
	}
}


再提供一个实验数据:

public static void main(String[] args){
		BinaryTreeNode root=new BinaryTreeNode(1, null, null);
		BinaryTreeNode node2=new BinaryTreeNode(2, null, null);
		BinaryTreeNode node3=new BinaryTreeNode(3, null, null);
		BinaryTreeNode node4=new BinaryTreeNode(4, null, null);
		BinaryTreeNode node5=new BinaryTreeNode(5, null, null);
		BinaryTreeNode node6=new BinaryTreeNode(6, null, null);
		BinaryTreeNode node7=new BinaryTreeNode(7, null, null);
		BinaryTreeNode node8=new BinaryTreeNode(8, null, null);
		
		root.setLeftChild(node2);
		root.setRightChild(node3);
		node2.setLeftChild(node4);
		node3.setLeftChild(node5);
		node3.setRightChild(node6);
		node5.setLeftChild(node7);
		node5.setRightChild(node8);
		
		root.print();
	}


结果:

1

2 3

4 5 6

7 8


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值