題目原型:
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] ]基本思路:
略
public ArrayList> levelOrder(TreeNode root) { ArrayList> list = new ArrayList>(); ArrayList nodeSet = new ArrayList(); ArrayList tmp ; ArrayListnumSet ; if(root!=null) { nodeSet.add(root); while(nodeSet.size()>0) { tmp = new ArrayList(); numSet = new ArrayList (); //添加到list中 for(TreeNode tn : nodeSet) numSet.add(tn.val); list.add(numSet); //求下一層的節點 for(TreeNode it : nodeSet) { if(it.left!=null) tmp.add(it.left); if(it.right!=null) tmp.add(it.right); } nodeSet = tmp; } } return list; }