用列队,BFS,时间复杂度和空间复杂度都是O(N)
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while(!q.isEmpty()){
//一层
ArrayList<Integer> row = new ArrayList<Integer>();
int count = q.size();
//这层的个数刚好是队列的长度
while(count-- >0){
TreeNode node = q.poll();
row.add(node.val);
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
res.add(row);
}
return res;
}
}
一开始是在offer左节点和右节点的顺序上做判断,测试了一下发现是错误的,第二个例子就错误了,后面就直接在row的数组中判断奇数=偶层,偶层把row数组反转一下,其余和上面上一题的层次遍历完全一致、时间复杂度和空间复杂度都是O(N)
import java.util.*;
import java.util.ArrayList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
Queue<TreeNode> q = new ArrayDeque<>();
if(pRoot==null) return new ArrayList<ArrayList<Integer>>(0);
q.offer(pRoot);
int index = 0;
while(!q.isEmpty()){
ArrayList<Integer> row = new ArrayList<>();
ArrayList<Integer> rever = new ArrayList<>();
int count = q.size();
index++;
while(count-- >0){
TreeNode node = q.poll();
row.add(node.val);
if(node.left!=null) q.offer(node.left);//奇数层从右到左
if(node.right!=null) q.offer(node.right);
}
if(index%2==0){
for(int i = row.size()-1; i>=0;i--){
rever.add(row.get(i));
}
res.add(rever);
}
else res.add(row);
}
return res;
}
}