题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
双98%通过;bfs,迭代;
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> levelOrder (TreeNode root) {
ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
if(root==null){
return ans;
}
ArrayList<Integer> cur=new ArrayList<>();
cur.add(root.val);
ArrayList<TreeNode> nodecur=new ArrayList<>();
nodecur.add(root);
while(cur.size()>0){
ans.add(cur);
ArrayList<Integer> parent =cur;
ArrayList<TreeNode> nodeparent =nodecur;
cur=new ArrayList<>();
nodecur=new ArrayList<>();
for(TreeNode node:nodeparent){
if(node.left!=null){
cur.add(node.left.val);
nodecur.add(node.left);
}
if(node.right!=null){
cur.add(node.right.val);
nodecur.add(node.right);
}
}
}
return ans;
// write code here
}
}