二叉树的层序遍历 II 20210105

0.题目

二叉树的层序遍历 II

给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自底向上的层序遍历为:

[
  [15,7],
  [9,20],
  [3]
]

1.BFS

1.1分析

主要思路:广度优先遍历+队列

  • 把每层的节点依次放到一个临时队列中;
  • 根据放入的size确定需要从队列中取出多少个元素节点;
  • 在取出的同时放入下一层的左右节点;
  • 直到队列为空;

1.2代码 1ms 38.5mb

public List<List<Integer>> levelOrderBottom(TreeNode root) {
	List<List<Integer>> resulst = new ArrayList<>();
	if (root == null) return resulst;
	Queue<TreeNode> queue = new LinkedList<TreeNode>();
	// 根节点放入队列中
	queue.offer(root);
	while (!queue.isEmpty()) {
		List<Integer> temp = new ArrayList<Integer>();
		// 队列的size决定上一层节点的个数
		int size = queue.size();
		for (int i = 0; i < size; i++) {
			TreeNode node = queue.poll();
			temp.add(node.val);
			// 取出节点的同时,放入左右节点,便于下次循环取出来
			if (node.left != null) {
				queue.add(node.left);
			}
			if (node.right != null) {
				queue.add(node.right);
			}
		}
		resulst.add(temp);
	}
	// 最后翻转数组即可
	Collections.reverse(resulst);
	return resulst;
}

2.DFS

2.1分析

主要思路:深度优先遍历

  • 首先遍历出最左侧的节点,顺带构造出每层的集合数组;
  • 右节点直接放入对应的集合数组即可;

示意图

2.2代码

public List<List<Integer>> levelOrderBottom(TreeNode root) {
	List<List<Integer>> result = new ArrayList<>();
	if (root == null) return result;
	dfs(root, result, 1);
	Collections.reverse(result);
	return result;
}
void dfs(TreeNode root, List<List<Integer>> result, int index) {
	if (root == null) return ;
	if (index > result.size()) result.add(new ArrayList<>());
	result.get(index-1).add(root.val);
	dfs(root.left, result, index+1);
	dfs(root.right, result, index+1);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值