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]
]
给定一个二叉树,输出它的每一层的结点。
使用两队列,一个保存当前处理的层,一个保存下一次要处理的层。只到每一层都处理完。
树结点类
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
算法实现类
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Deque<TreeNode> cur = new LinkedList<>();
Deque<TreeNode> sub = new LinkedList<>();
Deque<TreeNode> exc;
TreeNode node;
cur.addLast(root);
while (!cur.isEmpty()) {
List<Integer> layout = new LinkedList<>();
while (!cur.isEmpty()) {
node = cur.removeFirst();
layout.add(node.val);
if (node.left != null) {
sub.addLast(node.left);
}
if(node.right != null) {
sub.addLast(node.right);
}
}
exc = cur;
cur = sub;
sub = exc;
result.add(layout);
}
return result;
}
}
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。
版权声明:本文为博主原创文章,未经博主允许不得转载。
【LeetCode-面试算法经典-Java实现】【102-Binary Tree Level Order Traversal(二叉树层序遍历)】
原文地址:http://blog.csdn.net/derrantcm/article/details/47354349