1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ans = new ArrayList<List<Integer>>(); if(root == null){ return ans; } List<Integer> level = new ArrayList<>(); level.add(root.val); ans.add(level);
scan(root, ans, 2);
return ans; } public void scan(TreeNode root, List<List<Integer>> ans, int level){ List<Integer> l = new ArrayList<>(); if(ans.size() >= level){ l = ans.get(level-1); } if(root.left != null){ l.add(root.left.val); if(ans.size() >= level){ ans.set(level-1, l); } else{ ans.add(l); } scan(root.left, ans, level+1); } if(root.right != null){ l.add(root.right.val); if(ans.size() >= level){ ans.set(level-1, l); } else{ ans.add(l); } scan(root.right, ans, level+1); } }
|
Author:
Sheng Wang
Permalink:
https://shengwang.fun/2022/11/28/treescan/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE