剑指offer(59)按之字形顺序打印二叉树

package java_jianzhioffer_algorithm;
import java.awt.List;
/**
 * 题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,
 * 第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
 * @author hexiaoli
 * 思考:
 *   需要两个栈递归实现
 * 使用两个栈stack1,stack2。打印某一行结点时,把下一层的子结点保存到另一栈里:
a. 如果当前打印的是stack1出栈的奇数层结点,则先保存左子结点再保存右子结点到栈stack2里;
b. 如果当前打印的是stack2出栈的偶数层结点,则先保存右子结点再保存左子结点到栈stack1里。
--------------------- 
作者:Fan0628 
来源:CSDN 
原文:https://blog.csdn.net/Fan0628/article/details/89176973 
版权声明:本文为博主原创文章,转载请附上博文链接!  
 */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;
class TreeNodepz {
	int val = 0;
	TreeNodepz left = null;
	TreeNodepz right = null;
	public TreeNodepz(int val) {
		this.val = val;
	}
}
public class Printzhi {
	public  static ArrayList<ArrayList<Integer>> printzhi(TreeNodepz pRoot) {
        Stack<TreeNodepz> s1 = new Stack<>();
        Stack<TreeNodepz> s2 = new Stack<>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
       //初始层数为1
        int layer = 1;
        s1.push(pRoot) ;
        while(!s1.isEmpty()||!s2.isEmpty()) {
        	//奇数层
        	if((layer&1)==1) {
        		ArrayList<Integer> templist = new ArrayList<>();
        		while(!s1.isEmpty()) {
        			//出栈s1所有节点
            		TreeNodepz node = s1.pop();
            		if(node!=null) {
            			templist.add(node.val);
            			// 将所有结点的左右子节点从左至右入栈s2
            			s2.push(node.left);
            			s2.push(node.right);
            		}	
        		}
        		if(!templist.isEmpty()) {
        			result.add(templist);
        			layer++;
        		}
        	}else {
			//偶数层
        		ArrayList<Integer> templist = new ArrayList<>();
        		while(!s2.isEmpty()) {
        			//出栈s1所有节点
            		TreeNodepz node = s2.pop();
            		if(node!=null) {
            			templist.add(node.val);
            			// 将所有结点的左右子节点从左至右入栈s2
            			s1.push(node.left);
            			s1.push(node.right);
            		}	
        		}
        		if(!templist.isEmpty()) {
        			result.add(templist);
        			layer++;
        		}       		
			}
        }
        
        //打印结果
		for (ArrayList<Integer> arrayList : result) {
		    Iterator<Integer> it = arrayList.iterator();
		    while (it.hasNext()) {
		        int a = it.next();
		        System.out.print(a+" ");
		    }

		}       
        return result;
	}
	public static void main(String[] args) {
		TreeNodepz t1 = new TreeNodepz(8);
		TreeNodepz t2 = new TreeNodepz(6);
		TreeNodepz t3 = new TreeNodepz(10);
		TreeNodepz t4 = new TreeNodepz(5);
		TreeNodepz t5 = new TreeNodepz(7);
		TreeNodepz t6 = new TreeNodepz(9);
		TreeNodepz t7 = new TreeNodepz(11);		
		t1.left=t2;
		t1.right=t3;
		t2.left=t4;
		t2.right=t5;
		t3.left=t6;
		t3.right=t7;
		printzhi(t1);
	}

}

猜你喜欢

转载自blog.csdn.net/hxl0925/article/details/90044623