思路:利用队列进行广度优先遍历即可
注意点:ArrayList执行remove之后,索引i会立即重排,注意可能越界
code:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> res=new ArrayList<List<Integer>>();if(root==null) return res;List<TreeNode> queue = new ArrayList<TreeNode>();queue.add(root);while(queue.size()>0){int size=queue.size();List<Integer> t = new ArrayList<Integer>();for(int i=0;i<size;i++){t.add(queue.get(i).val);if(queue.get(i).left!=null){queue.add(queue.get(i).left);}if(queue.get(i).right!=null){queue.add(queue.get(i).right);} }for(int i=0;i<size;i++){queue.remove(0);}res.add(t);}return res;}
}