# 【LeetCode】二叉树算法题的几种解法与思路

【LeetCode】二叉树算法题的几种解法与思路

# 题目地址

https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

# 题目描述

输入: [3,9,20,null,null,15,7]



输入: [3,9,20,1,2,15,7]



# 解题源码

## 方法一

### 源码

public class Topic107_1 {

public static void main(String[] args) {
TreeNode root = new TreeNode(3);

TreeNode left = new TreeNode(9);
TreeNode right = new TreeNode(20);
root.left = left;
root.right = right;

TreeNode left1 = new TreeNode(15);
TreeNode right1 = new TreeNode(7);
right.left = left1;
right.right = right1;

TreeNode left2 = new TreeNode(2);
TreeNode right2 = new TreeNode(3);
left.left = left2;
left.right = right2;

List<List<Integer>> n = levelOrderBottom(root);

System.out.println(n);

}

public static List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> node = new ArrayList<>();
List<Integer> n = new ArrayList<>();
Map<Integer,List<Integer>> layer = new HashMap<>();
layer.put(0,n);

for (Integer integer : layer.keySet()) {
List<Integer> c = layer.get(integer);
if(c.size()>0) {
}
}
//倒叙输出
Collections.reverse(node);
return node;
}

/**
* 先递归，再倒叙输出
* 重点就是层级，利用Map的key存储层级
* @param root
* @param n
* @param layer
* @param level
*/
private static void addNode(TreeNode root, List<Integer> n,Map<Integer,List<Integer>> layer,Integer level) {
if(root==null){
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
List<Integer> next = new ArrayList<>();
if(layer.containsKey(level)){
next = layer.get(level);
}else {
layer.put(level,next);
}
if(left!=null){
}
if(right!=null){
}
}
}

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}



### 消耗

• 执行用时 : 2 ms
• 内存消耗 : 36.5 MB

## 方法二

### 源码

public class Topic107_2 {

public static void main(String[] args) {
TreeNode root = new TreeNode(3);

TreeNode left = new TreeNode(9);
TreeNode right = new TreeNode(20);
root.left = left;
root.right = right;

TreeNode left1 = new TreeNode(15);
TreeNode right1 = new TreeNode(7);
right.left = left1;
right.right = right1;

TreeNode left2 = new TreeNode(2);
TreeNode right2 = new TreeNode(3);
left.left = left2;
left.right = right2;

List<List<Integer>> n = levelOrderBottom(root);

System.out.println(n);

}

public static List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> node = new ArrayList<>();
if(root==null){
return node;
}

//倒叙输出
Collections.reverse(node);
return node;
}

/**
* 先递归，再倒叙输出
* 重点就是层级，直接使用ArrayList的层级
* @param root
* @param node
* @param level
*/
private static void addNode(TreeNode root,List<List<Integer>> node,Integer level) {
if(root==null){
return;
}
TreeNode left = root.left;
TreeNode right = root.right;
if(node.size() <= level){
}

if(left!=null){
}
if(right!=null){
}
}
}



### 消耗

• 执行用时 : 1 ms
• 内存消耗 : 36.5 MB

05-19 6861
05-28 404
04-10 2632
12-09 1317
12-05 221
04-19 390
04-03 2518
03-18 59

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。