leetcode102 二叉树的层次遍历
2023-09-27 14:25:55 时间
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [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 {
List<List<Integer>> levels = new ArrayList<List<Integer>>();
public void helper(TreeNode node, int level) {
if (levels.size() == level){
levels.add(new ArrayList<Integer>());
}
levels.get(level).add(node.val);
if (node.left != null)
helper(node.left, level + 1);
if (node.right != null)
helper(node.right, level + 1);
}
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return levels;
helper(root, 0);
return levels;
}
}
相关文章
- Java实现二叉树的创建、递归/非递归遍历
- Java二叉树链表的建立及四种遍历方法
- 二叉树的层序遍历 II
- 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树
- LeetCode高频题:二叉树的锯齿形(Z字形,之字形)层序遍历
- Morris遍历:与二叉树的递归遍历(DFS/BFS)不同,优化空间复杂度为o(1)
- 【Leetcode】102. 二叉树的层序遍历(中等)
- 1110 Complete Binary Tree (25 分)【难度: 一般 / 知识点: 判断完全二叉树】
- 二叉树——前序、中序、后序遍历
- 五三想休息,今天还学习,图解二叉树的层序遍历BFS(广度优先)模板,附面试题题解
- 【C++】二叉树之力扣经典题目1——详解二叉树的递归遍历,二叉树的层次遍历
- 剑指offer解法汇总79-判断是不是平衡二叉树
- LeetCode 144. 二叉树的前序遍历
- 二叉树遍历(层次)递归法
- 《剑指offer》-- 从上往下打印二叉树、二叉搜素树的后序遍历、二叉树中和为某一值的路径、二叉树与双向链表
- LeetCode098之验证二叉搜索树(相关话题:二叉树中序遍历的应用)
- 100、【树与二叉树】leetcode ——105. 从前序与中序遍历序列构造二叉树+106. 从中序与后序遍历序列构造二叉树(C++版本)
- 97、【树与二叉树】leetcode ——513.找树左下角的值:层次遍历+回溯法(C++版本)
- 90、【树与二叉树】leetcode ——104. 二叉树的最大深度:层次遍历+DFS+子问题分解(C++版本)
- 2022&2023华为OD机试 - 二叉树层次遍历(Python)
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- 堆算法(二叉树创建、遍历)
- leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 从中序与后序遍历序列构造二叉树(中等)