标签:
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 Solution { static class Queue { static final int MAX_SIZE = 1 << 10; private TreeNode list[]; int head; int tail; int cap; Queue() { list = new TreeNode[MAX_SIZE + 1]; head = 0; tail = 0; cap = MAX_SIZE + 1; } Queue(int size) { list = new TreeNode[size + 1]; head = 0; tail = 0; cap = size + 1; } boolean isEmpty() { return tail == head; } boolean isFull() { return (tail + 1) % cap == head; } void push(TreeNode node) { list[tail] = node; tail = (tail + 1) % cap; } TreeNode pop() { TreeNode top = list[head]; head = (head + 1) % cap; return top; } int size() { return (tail - head + cap) % cap; } TreeNode top() { return list[head]; } void print() { for (int i = head; i % cap != tail; i = (i + 1) % cap) { System.out.print(list[i].val + ","); } System.out.printf("\n"); } } static public boolean judge(LinkedList<List<TreeNode>> lists, Queue queue) { if (lists.isEmpty()) return true; if (queue.isEmpty()) return false; return !lists.getLast().contains(queue.top()); } static public void addQueue2List(Queue queue, List<List<Integer>> lists, LinkedList<List<TreeNode>> nodes) { List<Integer> vals = new ArrayList<Integer>(); List<TreeNode> nos = new ArrayList<TreeNode>(); for (int i = queue.head; i % queue.cap != queue.tail; i = (i + 1) % queue.cap) { vals.add(queue.list[i].val); nos.add(queue.list[i]); } lists.add(vals); nodes.add(nos) ; } public List<List<Integer>> levelOrder(TreeNode root) { Queue queue = new Queue(); LinkedList<List<Integer>> lists = new LinkedList<List<Integer>>(); LinkedList<List<TreeNode>> nodes = new LinkedList<List<TreeNode>>(); if (root != null) { queue.push(root); } while (!queue.isEmpty()) { //queue.print(); if (judge(nodes, queue)) { addQueue2List(queue, lists, nodes); } TreeNode node = queue.pop(); if (node.left != null) { queue.push(node.left); } if (node.right != null) { queue.push(node.right); } } return lists; } }
基本思路:观察每次进出队列时候的队列快照,发现在某一时刻,队列中的节点恰好为未访问的整个一层的节点。
核心在judge方法,会去检查已经访问的上一层次的节点中是否包含当前队列中的节点。只有judge返回true,
说明上一层的节点全部都出队了,可以安心访问下一层次的节点了。
标签:
原文地址:http://blog.csdn.net/wongson/article/details/44982503