递推
package leetcode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ls = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if (root == null)
return ls;
queue.add(root);
while (!queue.isEmpty()) { // 结合数学运算
int len = queue.size();
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < len; i++) { //len用于记录queue.size() 不会被for 里面的代码所影响 这道题 很妙
TreeNode T = queue.poll();
if (T.left != null)
queue.add(T.left);
if (T.right != null)
queue.add(T.right);
l.add(T.val);
}
ls.add(l);
}
return ls;
}
}
解法二
递归
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
levelOrder(root, list, 0);
return list;
}
public void levelOrder(TreeNode root, List<List<Integer>> list, int level){
if(root != null){
if(level > list.size() - 1){
List<Integer> nodes = new ArrayList<>();
list.add(nodes);
}
list.get(level).add(root.val);
levelOrder(root.left, list, level + 1);
levelOrder(root.right, list, level + 1);
}
}
}