Last active
May 15, 2019 08:30
-
-
Save RehmanaliMomin/86ad7e70c0e2e22b17a5839cf062b154 to your computer and use it in GitHub Desktop.
Tree - Level Order Traversal
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
| class GfG | |
| { | |
| void levelOrder(Node node) | |
| { | |
| int h = height(node); | |
| for(int i=0;i<h;i++){ | |
| lev(node,i); | |
| } | |
| } | |
| void lev(Node node,int level){ | |
| if(node==null) return; | |
| if(level==0) System.out.print(node.data+" "); | |
| else { | |
| lev(node.left,level-1); | |
| lev(node.right,level-1); | |
| } | |
| } | |
| int height(Node node){ | |
| if(node==null) return 0; | |
| else{ | |
| int lh = height(node.left); | |
| int rh = height(node.right); | |
| return lh>rh ? lh+1:rh+1; | |
| } | |
| } | |
| } | |
| Level Order traversal 2nd type, without recursion | |
| /** | |
| * Definition for a binary tree node. | |
| * public class TreeNode { | |
| * int val; | |
| * TreeNode left; | |
| * TreeNode right; | |
| * TreeNode(int x) { val = x; } | |
| * } | |
| */ | |
| class Solution { | |
| public List<List<Integer>> levelOrder(TreeNode root) { | |
| List<List<Integer>> list = new ArrayList<>(); | |
| level(list,0,root); | |
| return list; | |
| } | |
| public void level(List<List<Integer>> ans, int level, TreeNode root){ | |
| if(root==null) return; | |
| if(ans.size()==level){ | |
| List<Integer> newL = new ArrayList<>(); | |
| ans.add(newL); | |
| } | |
| List<Integer> list = ans.get(level); | |
| list.add(root.val); | |
| level(ans,level+1,root.left); | |
| level(ans,level+1,root.right); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment