Problem Source: https://leetcode.com/problems/binary-tree-level-order-traversal/
PackageCn.edu.shu;ImportJava.util.ArrayList;ImportJava.util.LinkedList;ImportJava.util.List;ImportJava.util.Queue;/** * * <p> * ClassName binarytreelevelordertraversal * </p> * <p> * Description Given a binary tre E, 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 20/15 7 return it level order Traversa L as: [[3], [9,20], * [15,7]] * </p> * * @author tkpad [email protected] * <p> * D ATE March 27, 2015 PM 10:53:07 * </p> * @version V1.0.0 * */ Public class binarytreelevelordertraversal {list<list<integer>> results =NewArraylist<list<integer>> (); list<integer> list =NewArraylist<integer> (); PublicList<list<integer>>Levelorder(TreeNode Root) {if(Root = =NULL) {return NewArraylist<list<integer>> (); } breadthfirstsearch (root);returnResults }//My main idea is to add a tag "null" after the last node in each layer, so that when you read NULL, you know that the layer is over and you need to join the collection Public void Breadthfirstsearch(TreeNode Root) {Queue<treenode> Queue =NewLinkedlist<treenode> (); Queue.add (root); Queue.add (NULL); TreeNode tn =NULL; while(! (queue.size () = =1&&NULL= = tn)) {tn = Queue.remove ();if(NULL= = tn) {Queue.add (NULL);//As a marker //Explain that the first layer has gone throughlist<integer> temp =NewArraylist<integer> (list); Results.add (temp); List.clear ();Continue; } list.add (Tn.val);if(Tn.left! =NULL) {Queue.add (tn.left); }if(Tn.right! =NULL) {Queue.add (tn.right); } } } Public Static void Main(string[] args) {TreeNode TN1 =NewTreeNode (5); TreeNode TN2 =NewTreeNode (4); TreeNode Tn3 =NewTreeNode (8); TreeNode Tn4 =NewTreeNode ( One); TreeNode tn5 =NewTreeNode ( -); TreeNode tn6 =NewTreeNode (4); TreeNode tn7 =NewTreeNode (7); Tn1.left = TN2; Tn2.left = Tn3; Tn3.left = Tn4;//tn1.right = TN5; //tn1.right = TN3; //Tn2.left = TN4; //tn2.right = TN5; //Tn4.left = TN6; //tn4.right = TN7; //Tn2.left = TN3;List<list<integer>> Levelorder =NewBinarytreelevelordertraversal (). Levelorder (TN1); System.out.println (Levelorder); }}
Binary Tree level Order traversal