题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
import java.util.*;
/*
- public class TreeNode {
- int val = 0;
- TreeNode left = null;
- TreeNode right = null;
- }
/
import java.util.;
public class Solution {
/**
*
- @param root TreeNode类
- @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList> levelOrder (TreeNode root) { ArrayList<ArrayList> arrayLists = new ArrayList<>(); if(root == null) return arrayLists; //TODO write code here LinkedList queue = new LinkedList<>(); queue.offer(root); return loop(queue, arrayLists); } private ArrayList<ArrayList> loop(Queue queue, ArrayList<ArrayList> arrayLists){ ArrayList list = new ArrayList<>(); LinkedList curQueue = new LinkedList<>(); while (!queue.isEmpty()){ TreeNode rootNode = queue.poll(); if(rootNode.left != null) curQueue.offer(rootNode.left); if(rootNode.right != null) curQueue.offer(rootNode.right); list.add(rootNode.val); } if(!list.isEmpty()) arrayLists.add(list); if(curQueue.isEmpty()) return arrayLists; return loop(curQueue, arrayLists); } }