Last active
April 28, 2020 14:05
-
-
Save AnjaliManhas/0536bc5e97604eccd2fdd58c6001fc47 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<List<Integer>>(); | |
if(root==null) return result; | |
Queue<TreeNode> q = new LinkedList<>(); | |
q.add(root); | |
while(q.size()>0){ | |
List<Integer> list = new ArrayList<>(); | |
int size = q.size(); | |
for(int i=0; i<size; i++){ | |
TreeNode node = q.poll(); | |
list.add(node.val); | |
if(node.left!=null) q.add(node.left); | |
if(node.right!=null) q.add(node.right); | |
} | |
result.add(0,list); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment