标签:
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/*
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>> result = new ArrayList<ArrayList<Integer>>();
if (pRoot == null) {
return result;
}
TreeNode point = null;
TreeNode end = null;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(pRoot);
point = pRoot;
end = pRoot;
ArrayList<Integer> list = new ArrayList<Integer>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // 出队列,然后分别将左右节点入队列
if (node.left != null) {
queue.offer(node.left);
point = node.left; // 更新当前这行最后一个进入队列的
}
if (node.right != null) {
queue.offer(node.right);
point = node.right;
}
list.add(node.val);
if (node == end) {
result.add(list);
list = new ArrayList<Integer>();
end = point; // 移到下一行中
}
}
return result;
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5721080.html