[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 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>&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 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

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.