-
-
Save InterviewBytes/33f581e55f2f2b8eaaf95f53d8c057c1 to your computer and use it in GitHub Desktop.
Level order bottom
This file contains 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
package com.interviewbytes.trees; | |
import java.util.ArrayList; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Queue; | |
public class LevelOrderBottom { | |
public List<List<Integer>> levelOrderBottom(TreeNode root) { | |
LinkedList<List<Integer>> deque = new LinkedList<>(); | |
if (root == null) return deque; | |
Queue<TreeNode> queue = new LinkedList<>(); | |
queue.offer(root); | |
while (!queue.isEmpty()) { | |
List<Integer> level = new ArrayList<>(); | |
int size = queue.size(); | |
while (size > 0) { | |
TreeNode n = queue.poll(); | |
level.add(n.val); | |
if (n.left != null) queue.offer(n.left); | |
if (n.right != null) queue.offer(n.right); | |
size--; | |
} | |
deque.offerFirst(level); | |
} | |
return deque; | |
} | |
} |
This file contains 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
package com.interviewbytes.trees; | |
public class TreeNode { | |
int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment