-
Notifications
You must be signed in to change notification settings - Fork 0
102. Binary Tree Level Order Traversal
Jacky Zhang edited this page Oct 30, 2016
·
2 revisions
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] ]
Tree类题目。
##Approach 1: DFS 可采用DFS的思想来解。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(root, 0, res);
return res;
}
private void helper(TreeNode node, int level, List<List<Integer>> res) {
if(node == null) return;
if(res.size() < level+1) {
res.add(new ArrayList<Integer>());
}
res.get(level).add(node.val);
helper(node.left, level+1, res);
helper(node.right, level+1, res);
}
}##Approach 2: BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
int size = queue.size();
List<Integer> curtLevel = new ArrayList<>();
for(int i = 0; i < size; i++) {
TreeNode node = queue.poll();
curtLevel.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
res.add(curtLevel);
}
return res;
}
}