问题:
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
解决:
① 问题的本质可以转化为层序遍历二叉树,然后将每层保存在链表中,反转链表即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution { //2ms
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>(); //注意格式
if(root == null) return res;
List<List<Integer>> list = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(! queue.isEmpty()){
int count = queue.size();
List<Integer> tmp = new ArrayList<>();
for (int i = 0;i < count ;i ++ ) {
TreeNode node = queue.poll();
tmp.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
list.add(tmp);
}
for (int i = list.size() - 1;i >= 0 ;i -- ) {
res.add(list.get(i));
}
return res;
}
}
② 在discuss中看到的,使用一个变量保存当前的层数。
public class Solution { // 2ms
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null) return res;
getList(root, 0, res);
return res;
}
public void getList(TreeNode root, int height, List<List<Integer>> res){
if(root == null) return;
if(res.size() == height){
ArrayList<Integer> temp = new ArrayList<>();
res.add(0,temp);
}
getList(root.left, height + 1, res);
getList(root.right,height + 1,res);
res.get(res.size() - height - 1).add(root.val);
}
}