题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
通过二叉树遍历添加节点,不必刻意一层层遍历,维护一个floor层数即可
需要注意的地方:l.size()其实就代表着层数,在floor大于l.size()的时候说明进入了新的层,创建一个ArrayList<integer>添加到l中</integer>
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { // write code here ArrayList<ArrayList<Integer>> res = new ArrayList<>(); preOrder(root, res, 1); return res; } private void preOrder(TreeNode root, ArrayList<ArrayList<Integer>> l, int floor) { if (root == null) { return; } if (floor > l.size()) { ArrayList<Integer> addList = new ArrayList<>(); l.add(addList); } l.get(floor - 1).add(root.val); preOrder(root.left, l, floor + 1); preOrder(root.right, l, floor + 1); } }