剑指 Offer 32 - I. 从上到下打印二叉树
题目:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
代码:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int[] levelOrder(TreeNode root) { 12 //空树 13 if(root==null){return new int[0]; } 14 //动态数组放入节点,模拟双端队列,同一层节点有序放入 15 List<TreeNode> list =new ArrayList<>(); 16 list.add(root); 17 int i=0; 18 while(i<list.size()){ 19 TreeNode temp=list.get(i); 20 if(temp.left!=null){list.add(temp.left);} 21 if(temp.right!=null){list.add(temp.right);} 22 i++; 23 } 24 //新建数组存放返回值 25 int len=list.size(); 26 int[] res=new int[len]; 27 int j=0; 28 for(TreeNode tn: list){ 29 res[j++]=tn.val; 30 } 31 return res; 32 } 33 }
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术