[leetcode]102 Binary Tree level Order traversal

Source: Internet
Author: User

https://oj.leetcode.com/problems/binary-tree-level-order-traversal/

http://blog.csdn.net/linhuanmars/article/details/23404111

/** * definition for binary tree * public class treenode {  *     int val; *     TreeNode left;  *     treenode right; *     treenode (int &NBSP;X)  { val = x; } * } */public class solution {     public list<list<integer>> levelorder (TreeNode root)  {                 // this  is how we use queue to iterate a tree.         // To let nodes on the same level be  returned in the same list, we can store an extra level  for each nodes.                list<list< Integer>> result = new arraylist<> ();         if  (root == null)              return result;        queue<nodewithlevel> queue  = new LinkedList<> ();         queue.offer (new  nodewithlevel (root, 0));        while  (!queue.isEmpty ( ))         {             nodewithlevel nodewithlevel = queue.poll ();             if  (Nodewithlevel.level == result.size ())         &nbSp;        result.add (new arraylist<integer> ());             result.get (NodeWithLevel.level). Add ( NodeWithLevel.node.val);                         if  (nodewithlevel.node.left != null )             {                 queue.offer (New nodewithlevel ( nodewithlevel.node.left, nodewithlevel.level + 1));             }            if   (Nodewithlevel.node.right != null)              {     &nbsP;          queue.offer (New nodewithlevel ( nodewithlevel.node.right, nodewithlevel.level + 1));             }        }                 return result;    }         private static class NodeWithLevel     {        TreeNode node;         int level;        nodewithlevel (TreeNode  Node, int level)         {             this.node = node;             this.level = level;        }    }} 


[leetcode]102 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.