Created
November 12, 2014 05:01
-
-
Save fever324/16175347d482b57c2d49 to your computer and use it in GitHub Desktop.
Binary Tree Reverse Level Order Traversal
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
/* | |
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). | |
For example: | |
Given binary tree {3,9,20,#,#,15,7}, | |
3 | |
/ \ | |
9 20 | |
/ \ | |
15 7 | |
return its bottom-up level order traversal as: | |
[ | |
[15,7], | |
[9,20], | |
[3] | |
] | |
*/ | |
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public List<List<Integer>> levelOrderBottom(TreeNode root) { | |
if(root == null) { | |
return new LinkedList<List<Integer>>(); | |
} | |
List<List<Integer>> l = new LinkedList<List<Integer>>(); | |
List<Integer> currentLevel = new LinkedList<Integer>(); | |
Queue<TreeNode> q = new LinkedList<TreeNode>(); | |
int prevN = 1; | |
int currentN = 0; | |
q.add(root); | |
while(!q.isEmpty()){ | |
TreeNode node = q.poll(); | |
currentLevel.add(node.val); | |
prevN--; | |
if(node.left != null) { | |
currentN++; | |
q.add(node.left); | |
} | |
if(node.right != null) { | |
currentN++; | |
q.add(node.right); | |
} | |
if(prevN == 0) { | |
l.add(0,currentLevel); | |
currentLevel = new LinkedList<Integer>(); | |
prevN = currentN; | |
currentN = 0; | |
} | |
} | |
if(currentLevel.size() != 0 ){ | |
l.add(0,currentLevel); | |
} | |
return l; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment