Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
这是一道很简单的BFS题,思路看一下题目立刻就有了,但是编码的过程中遇到了不少问题。
给定一个树,按照层续遍历,输出每一层的节点。当然要用队列来实现了!值得注意的是,怎么控制层数呢?
巧妙地引入两个list,current和next,分别代表当前层和下一层,当current当前层遍历完毕后,current<--next,再将next层重新定义。当然,只用一个list也可以实现,我的思路是每次将当前层数和node都加入队列。
实现起来的时候,我遇到了好几个问题,
1. Incompatible types List of List and ArrayList of ArrayList
2. Type mismatch: cannot convert from ArrayList to List
3. ArrayList<ArrayList<Integer>> cannot be converted to List<List<Integer>>
4. input[1] expected [[1]],我的代码却output [],发现忘了加“!”, while(!current.isEmpty())
最终借助stackoverflow都解决了,这是一个疑难点,我会专门写文章归纳,这里简单用代码归纳下,就是,
List<List<Integer>> result = new ArrayList<List<Integer>> ();
ArrayList<Integer> nodeValues = new ArrayList<Integer> ();
result.add(nodeValues);
好了,上代码吧,DEBUG了一个小时的代码.....
/**
* 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) {
List<List<Integer>> result = new ArrayList<List<Integer>> ();
ArrayList<Integer> nodeValues = new ArrayList<Integer> ();
if(root == null) {
return result;
}
LinkedList<TreeNode> current = new LinkedList<TreeNode>();
LinkedList<TreeNode> next = new LinkedList<TreeNode>();
current.add(root);
while(!current.isEmpty()) {
TreeNode node = current.remove();
nodeValues.add(node.val);
if(node.left != null) {
next.add(node.left);
}
if(node.right !=null) {
next.add(node.right);
}
if(current.isEmpty()) {
current = next;
next = new LinkedList<TreeNode> ();
result.add(nodeValues);
nodeValues = new ArrayList ();
}
}
return result;
}
}
********************分割线,错误代码********************
//这段代码就是刚开始错误重重不能通过的代码,放在这里以供日后比较。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>> ();//错误
ArrayList<Integer> nodeValues = new ArrayList<Integer> (); //错误
if(root == null) {
return result;
}
LinkedList<TreeNode> current = new LinkedList<TreeNode>();
LinkedList<TreeNode> next = new LinkedList<TreeNode>();
current.add(root);
while(current.isEmpty()) { //应该为不为空的时候
TreeNode node = current.remove();
if(node.left != null) {
next.add(node.left);
}
if(node.right !=null) {
next.add(node.right);
}
nodeValues.add(node.val);
if(current.isEmpty()) {
result.add(nodeValues);
current = next;
next = new LikedList<TreeNode> ();
nodeValues = new ArrayList<Integer> ();
}
}
return result;
}
}
没有评论:
发表评论