[
[3],
[9,20],
[15,7]
]
要求按层次输出, 所以每次需要记录一下当前层数的队列大小,然后遍历当前层的队列
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null) return res; List<TreeNode> nodelist = new ArrayList<>(); nodelist.add(root); while(!nodelist.isEmpty()){ int listlength = nodelist.size(); List<Integer> templ = new ArrayList<>(); for(int i =0; i<listlength;i++){ TreeNode tempn = nodelist.remove(0); templ.add(tempn.val); if(tempn.left != null) nodelist.add(tempn.left); if(tempn.right != null) nodelist.add(tempn.right); } res.add(templ); } return res; } }