Last active
April 28, 2020 14:05
-
-
Save AnjaliManhas/baa01c4968893b6a6d8b4ba526b7d4a7 to your computer and use it in GitHub Desktop.
Binary Tree Reverse Level Order Traversal- LeetCode: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
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
/** | |
* 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>> levelOrderBottom(TreeNode root) { | |
List<List<Integer>> result = new ArrayList<>(); | |
if(root == null){ | |
return result; | |
} | |
Queue<TreeNode> queue = new LinkedList<>(); | |
queue.add(root); | |
while(!queue.isEmpty()){ | |
List<Integer> temRes = new ArrayList<>(); | |
for(TreeNode node : queue){ | |
temRes.add(node.val); | |
} | |
result.add(temRes); | |
queue = makeQueue(queue); | |
} | |
Collections.reverse(result); | |
return result; | |
} | |
Queue<TreeNode> makeQueue(Queue<TreeNode> queue){ | |
Queue<TreeNode> queueCopy = new LinkedList<>(); | |
while(!queue.isEmpty()){ | |
TreeNode treeNode = queue.remove(); | |
if(treeNode.left != null) | |
queueCopy.add(treeNode.left); | |
if(treeNode.right != null) | |
queueCopy.add(treeNode.right); | |
} | |
return queueCopy; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment