[LeetCode] Binary Tree Level Order Traversal II

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


Question
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]
]

本题难度Easy。

【复杂度】
时间 O(N) 空间 O(2^(h-1))

【思路】
与​​[LeetCode]Binary Tree Zigzag Level Order Traversal​​相似的处理,把每层的​​list​​​查到结果​​ans​​的位置0上。

【代码】

/**
* 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) {
//require
List<List<Integer>> ans=new LinkedList<>();
Queue<TreeNode> q=new LinkedList<>();
if(root!=null)q.add(root);
//invariant
while(!q.isEmpty()){
int size=q.size();
List<Integer> list=new LinkedList<>();
for(int i=0;i<size;i++){
TreeNode n=q.remove();
list.add(n.val);
if(n.left!=null)q.add(n.left);
if(n.right!=null)q.add(n.right);
}
ans.add(0,list);
}
//ensure
return ans;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6