按之字形顺序打印二叉树

    请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层 按照从左到右的顺序打印,第三行再按照从左到右的顺序打印,其他行依次类推。

    思路:按照之字形顺序打印二叉树需要两个栈。当打印某一行节点时,把下一行的子节点保存到相应的栈里。如果当前打印的是奇数层,则先保存左子节点再保存右子节点到第

一个栈里;如果当前打印的是偶数层,则先保存右子节点再保存左子节点到第二个栈中。

import java.util.Stack;

class Node{
	int data;
	Node lChild;
	Node rChild;
	
	public Node(int data){
		this.data=data;
		this.lChild=null;
		this.rChild=null;
	}
}



public class Main{
	public static void main(String[] args) {
		int n=15;
		Node root;
		Node[] nodes=new Node[n];
		for(int i=0;i<n;i++){
			nodes[i]=new Node(i+1);
		}
		root=nodes[0];
		root.lChild=nodes[1];
		root.rChild=nodes[2];
		nodes[1].lChild=nodes[3];
		nodes[1].rChild=nodes[4];
		nodes[2].lChild=nodes[5];
		nodes[2].rChild=nodes[6];
		nodes[3].lChild=nodes[7];
		nodes[3].rChild=nodes[8];
		nodes[4].lChild=nodes[9];
		nodes[4].rChild=nodes[10];
		nodes[5].lChild=nodes[11];
		nodes[5].rChild=nodes[12];
		nodes[6].lChild=nodes[13];
		nodes[6].rChild=nodes[14];
		print(root);
	}
	
	public static void print(Node root){
		if(root==null){
			return;
		}
		Stack<Node> simple=new Stack<Node>();
		Stack<Node> odd=new Stack<Node>();
		Node temp;
		String temp_str="";
		simple.add(root);
		while(!simple.isEmpty()||!odd.isEmpty()){
			temp_str="";
			if(!simple.isEmpty()){ //奇数层不为空
				while(!simple.isEmpty()){
					temp=simple.pop();
					if(temp.lChild!=null) //存左孩子
					    odd.add(temp.lChild);
					if(temp.rChild!=null) //存右孩子
						odd.add(temp.rChild);
					temp_str=temp_str+temp.data+" ";
				}
				System.out.println(temp_str.substring(0,temp_str.length()-1));
			}
			
			temp_str="";
			if(!odd.isEmpty()){ //偶数层不为空
				while(!odd.isEmpty()){
					temp=odd.pop();
					if(temp.rChild!=null) //存右孩子
						simple.add(temp.rChild);
					if(temp.lChild!=null) //存左孩子
					    simple.add(temp.lChild);
					temp_str=temp_str+temp.data+" ";
				}
				System.out.println(temp_str.substring(0,temp_str.length()-1));
			}
			
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值