题目
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
无官方题解,可以参考102题的
感想
102题的代码,res改成LinkedList,然后插入list的时候add改成addFirst就行了,这种题目有点无聊了
执行用时 :3 ms, 在所有 Java 提交中击败了68.23%的用户
内存消耗 :36.6 MB, 在所有 Java 提交中击败了38.87%的用户
/**
* 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) {
LinkedList<List<Integer>> res = new LinkedList<>();//指定使用链表,不然用不了addFirst方法
if(root==null) return res;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.add(root);
TreeNode nextFirst = null;
TreeNode temp = null;
List<Integer> list = new LinkedList<>();
while(!queue.isEmpty()){
temp = queue.poll();
if(temp==nextFirst) {
nextFirst=null;
res.addFirst(list);//头插法
list = new LinkedList<>();
}
list.add(temp.val);
if(temp.left!=null){
queue.add(temp.left);
if(nextFirst==null) nextFirst = temp.left;
}
if(temp.right!=null){
queue.add(temp.right);
if(nextFirst==null) nextFirst = temp.right;
}
}
if(list.size()>0) res.addFirst(list);//头插法
return res;
}
}