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] ]
对每一层的节点都用ArrayList<TreeNode> cur保存,每次循环时把cur里每个非空节点值拿出来并保存到ArrayList<Integer> temp中, 并且子节点保存到新的ArrayList<TreeNode>中。最后如果 temp 非空,就加入到结果集中。最后cur 指向新的ArrayList<TreeNode>。
1 public List<List<Integer>> levelOrder(TreeNode root) { 2 List<List<Integer>> re = new ArrayList<List<Integer>>(); 3 List<TreeNode> lst = new ArrayList<TreeNode>(); 4 lst.add(root); 5 while(lst.size()>0){ 6 List<Integer> temp = new ArrayList<Integer>(); 7 List<TreeNode> childrenlst = new ArrayList<TreeNode>(); 8 for(int i=0;i<lst.size();i++){ 9 TreeNode curNode = lst.get(i); 10 if(curNode!=null){ 11 temp.add(lst.get(i).val); 12 childrenlst.add(curNode.left); 13 childrenlst.add(curNode.right); 14 } 15 } 16 if(temp.size()>0) 17 re.add(temp); 18 lst = childrenlst; 19 } 20 return re; 21 }
Level Order Traverse II 就是反一反。