菜鸡每日一题系列打卡102天
每天一道算法题目
小伙伴们一起留言打卡
坚持就是胜利,我们一起努力!
题目描述(引自LeetCode)
给你一个二叉树,请你返回其按层序遍历得到的节点值。(即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
题目分析
这又是一道二叉树的题目,二叉树常见的遍历方式有前序遍历、中序遍历、后序遍历、层序遍历,而本文要考查的就是其中的层序遍历。需要回顾二叉树相关知识的可以看这篇菜鸡的算法修炼——二叉树(重建二叉树)。
普通的层序遍历非常简单,而本题的难点在于需要按层记录遍历结果。因此,需要记录当前层是否已经遍历完毕。
二叉树是递归定义的数据结构,关于其层次遍历,我们可以采用递归或迭代的方式进行求解。为了给大家提供不同的思路,菜鸡在本文中将采用上述两种方式进行解答。话不多说,上代码!
代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// 递归中序遍历
class Solution {
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
visit(root, 0);
return result;
}
private void visit(TreeNode node, int current){
if (node == null) {
current--;
return;
}
if (result.size() == current) result.add(new ArrayList<>());
result.get(current).add(node.val);
visit(node.left, current + 1);
visit(node.right, current + 1);
current--;
return;
}
}
// 迭代中序遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> tmp = new ArrayList<>();
while (size-- > 0) {
TreeNode current = queue.poll();
tmp.add(current.val);
if (current.left != null) queue.offer(current.left);
if (current.right != null) queue.offer(current.right);
}
result.add(tmp);
}
return result;
}
}
代码分析
对代码进行分析,不妨设二叉树的结点个数为n,则:
递归:时间复杂度为O(n),空间复杂度为O(n)。
迭代:时间复杂度为O(n),空间复杂度为O(n)。
执行结果
递归的执行结果
迭代的执行结果
福利抽奖????
学习 | 工作 | 分享
????长按关注“有理想的菜鸡”
只有你想不到,没有你学不到