描述 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。 例如: 给定的二叉树是{1,2,3,#,#,4,5} 该二叉树多行打印层序遍历的结果是 [ [1], [2,3], [4,5] ]
示例1
输入: {1,2,3,#,#,4,5} 返回值: [[1],[2,3],[4,5]]
示例2
输入: {8,6,10,5,7,9,11} 返回值: [[8],[6,10],[5,7,9,11]]
示例3
输入: {1,2,3,4,5} 返回值: [[1],[2,3],[4,5]]
思路: 层次遍历 时间复杂度:O(N) 空间复杂度:O(1)
代码
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
if (pRoot == null) {
return res;
}
ArrayList<TreeNode> nodeList = new ArrayList<>();
nodeList.add(pRoot);
while (nodeList.size() != 0) {
ArrayList<TreeNode> tempList = new ArrayList<>();
ArrayList<Integer> valueList = new ArrayList<>();
for (int i = 0; i < nodeList.size(); i++) {
valueList.add(nodeList.get(i).val);
if (nodeList.get(i).left != null) {
tempList.add(nodeList.get(i).left);
}
if (nodeList.get(i).right != null) {
tempList.add(nodeList.get(i).right);
}
}
res.add(valueList);
nodeList = tempList;
}
return res;
}
}
|