"102-binary Tree Level Order traversal (binary tree sequence traversal)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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]]
Main Topic
Given a binary tree, output the nodes of each of its layers.
Thinking of solving problems
Use two queues, one to save the current processing layer, and one to save the next one to process. It's all done at every level.
Code Implementation
Tree Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm implementation class
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>> re Sult = new arraylist<> ();if(root = null) {returnResult } 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); }returnResult }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47354349"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-Interview Algorithm classic-java implementation "102-binary Tree Level order traversal (binary sequence traversal)"