[Leetcode] [Java] Binary Tree level Order traversal

Source: Internet
Author: User

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>&gt          ;();          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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.