Created
May 25, 2019 12:55
-
-
Save madhur/655baa67366d6d672b37ed8068ebd88d to your computer and use it in GitHub Desktop.
Print a Binary Tree Level by Level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // java.util.* and java.util.streams.* have been imported for this problem. | |
| // You don't need any other imports. | |
| public ArrayList<ArrayList<Integer>> printLevelByLevel(TreeNode root) { | |
| ArrayList<Integer> nodeList = new ArrayList<Integer>(); | |
| ArrayList<Integer> levelList = new ArrayList<Integer>(); | |
| ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>(); | |
| if (root == null) { | |
| return myList; | |
| } | |
| Queue<TreeNode> currentQ = new LinkedList<TreeNode>(); | |
| Queue<TreeNode> nextQ = new LinkedList<TreeNode>(); | |
| currentQ.add(root); | |
| while(!currentQ.isEmpty()) { | |
| while(!currentQ.isEmpty()) { | |
| TreeNode node = currentQ.remove(); | |
| if (node != null) { | |
| levelList.add(node.data); | |
| if(node.left!=null) | |
| nextQ.add(node.left); | |
| if(node.right!=null) | |
| nextQ.add(node.right); | |
| } | |
| } | |
| myList.add(levelList); | |
| levelList =new ArrayList<Integer>(); | |
| while(!nextQ.isEmpty()) { | |
| currentQ.add(nextQ.remove()); | |
| } | |
| } | |
| return myList; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment