Topic:
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 / 7
Return its level order traversal as:
[ 3], [9,20], [15,7]]
Test instructions
Given a binary tree, traverse all the nodes of the binary tree according to the order of the layers (i.e., from left to right layer)
For example, given a binary tree {3,9,20,#,#,15,7} ,
3 / 9 / 7
The layer traversal that returns it is:
[ 3], [9,20], [15,7]]
Algorithm Analysis:
The problem is a hierarchical first traversal of the two-fork tree, which is primarily used as a queue for storage, by placing the left child and right child of each node in the queue, and then removing the elements from the queue each time. Better understand, directly on the code.
AC Code:
public class Solution {private static TreeNode root, public static arraylist<arraylist<integer>> Levelord ER (TreeNode root) {arraylist<arraylist<integer>> res = new Arraylist<arraylist<integer>> ;(); if (root = null) {return res; } arraylist<integer> tmp = new arraylist<integer> (); queue<treenode> queue = new linkedlist<treenode> (); Queue.offer (root); int num; Boolean reverse = false; while (!queue.isempty ()) {num = Queue.size (); Each time through this determined finally the number of teams tmp.clear (); for (int i = 0; i < num; i++)//1 parent in queue. into two children, out of 2 fathers, and 4 sons; out of 4 fathers. Enter 8 Sub {TreeNode node = Queue.poll (); Tmp.add (Node.val); if (node.left! = null) Queue.offer (node.left); if (node.right! = null) Queue.offer(Node.right); } res.add (New Arraylist<integer> (TMP)); } return res; } }
[Leetcode] [Java] Binary Tree level Order traversal