您的位置:首页 > 其它

leetcode Binary Tree Level Order Traversal

2015-05-29 21:57 239 查看
题目链接链接

思想:广度优先算法

/**
* 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入队的东西取出来要记得剔除
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: