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 {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/**
* Definition for binary tree
* 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>> res = new ArrayList<List<Integer>>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
int qSize;
while (!queue.isEmpty()) {
List<Integer> list = new ArrayList<Integer>();
qSize = queue.size();
for (int i = 0; i < qSize; i++) {
TreeNode cur = queue.poll();
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
list.add(cur.val);
}
res.add(new ArrayList(list));
}
return res;
}
}
直接一次 AC 的题目,这里注意几个基础知识和方法:
queue 是用linkedlist 实现的,但是queue不能使用 likedlist 自己的方法。
另外 queue 的 isEmpty() 方法 是 inherited from interface java.util.collection.
而stack 是用 empty()来判断,不用记混了。
本文介绍了一种解决二叉树层次遍历问题的方法,并通过使用队列实现了从上到下、从左到右的层次遍历。文章还强调了队列与栈的区别及其在遍历过程中的应用。
1313

被折叠的 条评论
为什么被折叠?



