Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Roger7410/328488b3932d080c181a4dd70cd3326f to your computer and use it in GitHub Desktop.

Select an option

Save Roger7410/328488b3932d080c181a4dd70cd3326f to your computer and use it in GitHub Desktop.
public class Solution {
// public List<List<Integer>> levelOrder(TreeNode root) {
// List<List<Integer>> result = new ArrayList<>();
// Queue<TreeNode> queue = new LinkedList<>();
// if(root == null) return result;
// queue.add(root);
// while(!queue.isEmpty()){
// int size = queue.size();
// List<Integer> tmpList = new ArrayList<>();
// for(int i=0; i<size; i++){
// TreeNode node = queue.poll();
// tmpList.add(node.val);
// if(node.left != null){
// queue.add(node.left);
// }
// if(node.right != null){
// queue.add(node.right);
// }
// }
// result.add(tmpList);
// }
// return result;
// }
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
levelHelper(res, root, 0);
return res;
}
public void levelHelper(List<List<Integer>> res, TreeNode root, int height) {
if (root == null) return;
if (height >= res.size()) {
res.add(new LinkedList<Integer>());
}
res.get(height).add(root.val);
levelHelper(res, root.left, height+1);
levelHelper(res, root.right, height+1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment