题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
public class Solution { public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { // 使用先序遍历的方法 ArrayList<ArrayList<Integer>> res = new ArrayList<>(new ArrayList<>()); if (root == null) return res; levelHandler(root, 0, res); return res; } private void levelHandler(TreeNode root, int level, ArrayList<ArrayList<Integer>> res) { if(root == null) return; if (res.size() <= level) res.add(new ArrayList<>()); res.get(level).add(root.val); levelHandler(root.left, level + 1, res); levelHandler(root.right, level + 1, res); } }
使用前序遍历的思想,level表示层级,刚开始从0开始(根节点)