import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {///经典的广搜例题 只要加上记录每层的结点数目即可
ArrayList<ArrayList<Integer>>lists=new ArrayList<ArrayList<Integer>>();
if(pRoot==null) return lists;
Queue<TreeNode>queue=new LinkedList<TreeNode>();
queue.offer(pRoot);
int m=1;//当前层的节点数
int n=0;//下一层的节点数
while(!queue.isEmpty()){
ArrayList<Integer>list=new ArrayList<Integer>();
while(m>0){
TreeNode tree=queue.poll();
list.add(tree.val);
if(tree.left!=null){
queue.offer(tree.left);
n++;
}
if(tree.right!=null){
queue.offer(tree.right);
n++;
}
m--;
}
m=n;
n=0;
lists.add(list);
}
return lists;
}
}
把二叉树打印成多行
最新推荐文章于 2020-10-31 08:55:16 发布