题目链接链接
思想:广度优先算法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
TreeNode endLineFlag=new TreeNode(0);
List<List<Integer>> myArray= new LinkedList<List<Integer>> ();
LinkedList<Integer> workContiner=new LinkedList<Integer>();
ArrayDeque<TreeNode> queue=new ArrayDeque<TreeNode>();
if(root==null)
{
return myArray;
}
queue.addLast(root);
queue.addLast(endLineFlag);
TreeNode current=null;
while(queue.size()>1)
{
current=queue.remove();
if(current==endLineFlag)
{
myArray.add(workContiner);
workContiner=new LinkedList<Integer>();
queue.addLast(endLineFlag);
continue;
}
workContiner.add(current.val);
if(current.left!=null)
{
queue.add(current.left);
}
if(current.right!=null)
{
queue.add(current.right);
}
}
myArray.add(workContiner);
return myArray;
}
}
遇到的错误
1空链表不等于null
2入队的东西取出来要记得剔除