标签:class tree span link add ret while color linked
import java.util.ArrayList; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.*; public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> arrayList = new ArrayList<ArrayList<Integer>>(); if(pRoot == null){ return arrayList; } Queue<TreeNode> q1 = new LinkedList<TreeNode>(); q1.add(pRoot); Queue<TreeNode> q2 = new LinkedList<TreeNode>(); while(!q1.isEmpty() || !q2.isEmpty()){ if(!q1.isEmpty()){ ArrayList<Integer> list = new ArrayList<Integer>(); while(!q1.isEmpty()){ TreeNode node = q1.poll(); list.add(node.val); if(node.left != null){ q2.add(node.left); } if(node.right != null){ q2.add(node.right); } } arrayList.add(list); }else{ ArrayList<Integer> list = new ArrayList<Integer>(); while(!q2.isEmpty()){ TreeNode node = q2.poll(); list.add(node.val); if(node.left != null){ q1.add(node.left); } if(node.right != null){ q1.add(node.right); } } arrayList.add(list); } } return arrayList; } }
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
标签:class tree span link add ret while color linked
原文地址:https://www.cnblogs.com/q-1993/p/10966485.html