层序遍历写法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] levelOrder(TreeNode root) {
if(root == null) return new int[0];
Queue<TreeNode> q = new LinkedList<>();
ArrayList<Integer> array = new ArrayList<>();
q.offer(root);
while(!q.isEmpty()){
TreeNode tree = q.poll();
array.add(tree.val);
if(tree.left != null) q.offer(tree.left);
if(tree.right != null) q.offer(tree.right);
}
int[] res = new int[array.size()];
for(int i=0; i<array.size(); i++){
res[i] = array.get(i);
}
return res;
}
}