剑指offer(60)把二叉树打印成多行

package java_jianzhioffer_algorithm;
/**
 * 题目:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
 * @author hexiaoli
 * 思考:
 *  1)加入两个变量,toBePrinted表示当前还没打印的节点数,nextLevel表示下一层的节点数。
 *  2)使用递归的方法进行前序遍历,传递深度,递归深入一层扩容一层数组。作者:Fan0628
 */
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.RootPaneContainer;
class TreeNodep{
    int val = 0;
    TreeNodep left = null;
    TreeNodep right = null;
    public TreeNodep(int val) {
        this.val = val;
    }
}
public  class Print {
	public static ArrayList<ArrayList<Integer> > print1(TreeNodep pRoot){
		ArrayList<ArrayList<Integer>>  result = new ArrayList<>();
		ArrayList<Integer> tempList = new ArrayList<>();
		ArrayList<TreeNodep> queue = new ArrayList<>();
		// Queue<TreeNode> queue = new LinkedList<>();
		if(pRoot == null ) {
			return result;
		}
		// 在队列中加入根节点
		queue.add(pRoot);
		int nextLevel = 0;
		int toBePrint = 1;
		while(!queue.isEmpty()) {
			// 取出队列头结点
			TreeNodep temp = queue.remove(0);
			--toBePrint;
			tempList.add(temp.val);
			System.out.print(temp.val+" ");
			// 如果取出的队列头结点有左子节点,则加入到队列尾,offer
			if(temp.left !=null) {
				queue.add(temp.left);
				nextLevel++;
			}
			// 如果取出的队列头结点有右子节点,则加入到队列尾
			if(temp.right !=null) {
				queue.add(temp.right);
				nextLevel++;
			}
			if(toBePrint == 0) {
				result.add( new ArrayList<Integer>(tempList));
				tempList.clear();
				System.out.print('\n');
				toBePrint = nextLevel;
				nextLevel=0;
			}
		}
		
		return result;		
	}
	public static ArrayList<ArrayList<Integer>> print2(TreeNodep pRoot){
		ArrayList<ArrayList<Integer>> list = new ArrayList<>();
		Depth(pRoot,1,list);
		for (ArrayList<Integer> arrayList : list) {
		    Iterator<Integer> it = arrayList.iterator();
		    while (it.hasNext()) {
		        int a = it.next();
		        System.out.print(a+" ");
		    }
		    System.out.println();
		}
		return list;
	}
	public static void Depth(TreeNodep pRoot,int depth,ArrayList<ArrayList<Integer>> list) {
		if(pRoot == null) {
			return ;
		}
		// 当前深度值大于list的容量,则进行扩容
		if(depth>list.size()) {
			list.add(new ArrayList<Integer>());
		}
		// 将结点值存入list对应层
		list.get(depth - 1).add(pRoot.val);
        // 递归对左子结点、右子结点进行操作
        Depth(pRoot.left, depth + 1, list);
        Depth(pRoot.right, depth + 1, list);
	}
	public static void main(String[] args) {
		TreeNodep t1 = new TreeNodep(8);
		TreeNodep t2 = new TreeNodep(6);
		TreeNodep t3 = new TreeNodep(10);
		TreeNodep t4 = new TreeNodep(5);
		TreeNodep t5 = new TreeNodep(7);
		TreeNodep t6 = new TreeNodep(9);
		TreeNodep t7 = new TreeNodep(11);		
		t1.left=t2;
		t1.right=t3;
		t2.left=t4;
		t2.right=t5;
		t3.left=t6;
		t3.right=t7;
		print1(t1);

		print2(t1);
	}

}

猜你喜欢

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