Created
October 12, 2016 21:53
-
-
Save Roger7410/328488b3932d080c181a4dd70cd3326f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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