需要学习资料的+微信公众号 学习资源后台找我
本人比较忙 我看到了会在后台帮你,谢谢关注啦
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
代码如如下:
import java.util.ArrayList;
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) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
if(pRoot == null)return lists;
ArrayList<Integer> list = new ArrayList<Integer>();
TreeNode last = pRoot;
TreeNode nlast = pRoot;
queue.add(pRoot);
while(!queue.isEmpty()){
TreeNode tmp =queue.poll();
list.add(tmp.val);
if(tmp.left != null){
queue.add(tmp.left);
nlast = tmp.left;
}
if(tmp.right != null){
queue.add(tmp.right);
nlast = tmp.right;
}
if(tmp == last){
last = nlast;
lists.add(list);
list = new ArrayList<Integer>();
}
}
return lists;
}
}