For example:
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what
"{1,#,2,3}"
means? Java Code
public List> levelOrder(TreeNode root) { List
> res = new ArrayList
>(); Queue
tmp = new LinkedList (); if(root == null) return res; tmp.add(root); while(!tmp.isEmpty()){ int size = tmp.size(); List level = new ArrayList (); for(int i = 0; i < size; i++){ TreeNode node = tmp.poll(); level.add(node.val); if(node.left != null) tmp.add(node.left); if(node.right != null) tmp.add(node.right); } res.add(level); } return res; }
No comments:
Post a Comment