Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
BFS
广度遍历写法是用一个队列,依次将各行节点存进去,poll 出来时将 val 存到 list 时顺便添加其子节点到队列中。代码如下:
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>> ();
if(root == null) return list;
Queue<TreeNode> q = new LinkedList<TreeNode> ();
q.add(root);
while(!q.isEmpty()) {
int size = q.size();
ArrayList<Integer> temp = new ArrayList<Integer> ();
for(int i = 0; i < size; i++) {
TreeNode poll = q.poll();
if(poll.left != null)q.add(poll.left);
if(poll.right != null)q.add(poll.right);
temp.add(poll.val);
}
list.add(temp);
}
return list;
}
}
DFS
深搜,创建一个函数,参数为所要返回的 list,节点和该节点所在的 level,当 list 没有该 level 的子 list 时,则创建。每次将 val 存到对应level 的子list。之后递归调用。代码如下:
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<List<Integer>> ();
addList(list, root, 0);
return list;
}
private void addList(List<List<Integer>> list, TreeNode node, int level) {
if(node == null) return;
if(list.size() == level) list.add(new ArrayList<Integer> ());
List<Integer> temp = list.get(level);
temp.add(node.val);
addList(list, node.left, level + 1);
addList(list, node.right, level + 1);
}
}