My code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
int levelSize = q.size();
ArrayList<Integer> level = new ArrayList<Integer>();
for (int i = 0; i < levelSize; i++) {
TreeNode temp = q.poll();
level.add(temp.val);
if (temp.left != null)
q.offer(temp.left);
if (temp.right != null)
q.offer(temp.right);
}
result.add(level);
}
Collections.reverse(result);
return result;
}
}
My test result:
主要就是反转下。正好今天学习了
Collections.reverse(); 就用上了,没什么难的。
**
总结: level order of tree. Collections.reverse();
**
Anyway, Good luck, Richardo!
My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null)
return ret;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
int levelSize = q.size();
ArrayList<Integer> group = new ArrayList<Integer>();
for (int i = 0; i < levelSize; i++) {
TreeNode temp = q.poll();
group.add(temp.val);
if (temp.left != null)
q.offer(temp.left);
if (temp.right != null)
q.offer(temp.right);
}
ret.add(group);
}
Collections.reverse(ret);
return ret;
}
}
void Collections.reverse(xxx);
Anyway, Good luck, Richardo!
iteration 的方法和上面一模一样,就不写了。最后reverse
下面放下 recursion做法,其实也差不多。
My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
helper(root, 0, ret);
Collections.reverse(ret);
return ret;
}
private void helper(TreeNode root, int level, List<List<Integer>> ret) {
if (root == null) {
return;
}
if (level > ret.size() - 1) {
ret.add(new ArrayList<Integer>());
}
ret.get(level).add(root.val);
helper(root.left, level + 1, ret);
helper(root.right, level + 1, ret);
}
}
就多加一个 Collections.reverse(xxx);
这个函数返回类型是 void
Anyway, Good luck, Richardo! -- 09/06/2016