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 in the order of the layers (i.e., from left to right layers)
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 hierarchy-first traversal of a two-fork tree, which is primarily stored as a queue, 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 understanding, 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 determines the final number of teams tmp.clear (); for (int i = 0; i < num; i++)//1 fathers in the queue, two children, 2 fathers, 4 children, 4 fathers, 8 children {TreeNode node = Queue.po ll (); 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; } }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Binary Tree level Order traversal