Link: http://oj.leetcode.com/problems/binary-tree-level-order-traversal/
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / 2 3 / 4 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { 12 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 13 if (root == null) 14 return result; 15 // the algo is based on bfs, here I need a queue data structure 16 ArrayList<TreeNode> queue = new ArrayList<TreeNode>(); 17 queue.add(root); 18 ArrayList<Integer> root_value = new ArrayList<Integer>(); 19 // this is a special case, the value of the root should 20 // be added first. 21 root_value.add(root.val); 22 result.add(root_value);// 23 while (!queue.isEmpty()) { 24 // all the nodes of the next level 25 ArrayList<TreeNode> next_level = new ArrayList<TreeNode>(); 26 for (TreeNode t : queue) { 27 // iterate through the queue 28 ArrayList<TreeNode> temp_treenode = getChildren(t); 29 // append all of the next level node to next_level 30 next_level.addAll(temp_treenode); 31 } 32 // clear the queue 33 queue = new ArrayList<>(); 34 // special case, if there's no next level nodes 35 if (next_level.size() != 0) { 36 queue.addAll(next_level); 37 result.add(getValue(next_level)); 38 } 39 } 40 return result; 41 } 42 43 public ArrayList<Integer> getValue(ArrayList<TreeNode> list) { 44 ArrayList<Integer> result = new ArrayList<Integer>(); 45 for (TreeNode t : list) { 46 result.add(t.val); 47 } 48 return result; 49 } 50 51 public ArrayList<TreeNode> getChildren(TreeNode root) { 52 ArrayList<TreeNode> result = new ArrayList<TreeNode>(); 53 if (root.left != null) 54 result.add(root.left); 55 if (root.right != null) 56 result.add(root.right); 57 return result; 58 } 59 }
开始很纠结Queue的操作。。后来干脆遍历queue,遍历完清空queue,然后再把下一层的node再加入queue