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; } }
原文地址:https://www.cnblogs.com/q-1993/p/10966485.html
时间: 2024-10-10 04:20:54