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?
Solution:
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 List
> levelOrder(TreeNode root) {12 List
> res = new ArrayList
>();13 List oneRes = new ArrayList ();14 if (root==null){15 return res;16 }17 18 List lastLevel = new ArrayList ();19 lastLevel.add(root);20 oneRes.add(root.val);21 res.add(oneRes);22 List curLevel;23 while (lastLevel.size()!=0){24 oneRes = new ArrayList ();25 curLevel = new ArrayList ();26 for (int i=0;i