目录LeetCode 102. 二叉树的层序遍历题目思路代码LeetCode 543. 二叉树的直径题目思路代码 总结超级好记题目给你二叉树的根节点root返回其节点值的层序遍历。即逐层地从左到右访问所有节点。思路用递归模拟层次遍历记录当前节点深度自动创建对应层的集合遵循中 → 左 → 右顺序添加元素无需队列纯递归实现 BFS 效果代码/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val val; * this.left left; * this.right right; * } * } */ class Solution { // 存储最终层序结果 private ListListInteger result new ArrayList(); public ListListInteger levelOrder(TreeNode root) { // 递归遍历初始深度为 0 chunk(root, 0); return result; } // 递归函数node 当前节点deep 当前深度 private void chunk(TreeNode node, int deep) { if (node null) return; // 到达新深度创建新列表 if (result.size() deep) { result.add(new ArrayList()); } // 把当前节点值加入对应层 result.get(deep).add(node.val); // 递归左右子树深度 1 chunk(node.left, deep 1); chunk(node.right, deep 1); } }LeetCode 543. 二叉树的直径题目给定一棵二叉树你需要计算它的直径长度。一棵二叉树的直径长度是任意两个节点路径长度中的最大值。这条路径可能穿过也可能不穿过根节点。思路直径 左子树最大深度 右子树最大深度使用后序遍历先算左、再算右、最后更新答案dfs返回值以当前节点为根的最长链长度全局变量记录直径最大值代码/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val val; * this.left left; * this.right right; * } * } */ class Solution { // 记录最终直径答案 private int ans 0; public int diameterOfBinaryTree(TreeNode root) { dfs(root); return ans; } // 返回以当前节点为根的最长链长度 private int dfs(TreeNode node) { if (node null) return -1; // 左子树链长 1 int leftLen dfs(node.left) 1; // 右子树链长 1 int rightLen dfs(node.right) 1; // 更新直径左 右 ans Math.max(ans, leftLen rightLen); // 返回当前节点的最长链 return Math.max(leftLen, rightLen); } } 总结超级好记层序遍历递归版按深度创建集合中 → 左 → 右添加纯递归实现 BFS代码极短二叉树直径直径 左最深 右最深后序遍历全局变量记录最大值