Created
August 24, 2013 01:59
-
-
Save charlespunk/6325584 to your computer and use it in GitHub Desktop.
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
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], | |
] |
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
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
public class Solution { | |
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
LinkedList<ArrayList<Integer>> all = new LinkedList<ArrayList<Integer>>(); | |
if(root == null) return new ArrayList<ArrayList<Integer>>(all); | |
Queue<TreeNode> q = new LinkedList<TreeNode>(); | |
q.offer(root); | |
while(!q.isEmpty()){ | |
ArrayList<Integer> one = new ArrayList<Integer>(); | |
for(TreeNode node: q) one.add(node.val); | |
all.addFirst(one); | |
Queue<TreeNode> qNext = new LinkedList<TreeNode>(); | |
while(!q.isEmpty()){ | |
TreeNode node = q.poll(); | |
if(node.left != null) qNext.offer(node.left); | |
if(node.right != null) qNext.offer(node.right); | |
} | |
q = qNext; | |
} | |
return new ArrayList<ArrayList<Integer>>(all); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment