剑指offer22题
import java.util.ArrayList; class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } /** * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 * 思路 * 打印一层,遍历一层 */ public class Solution22 { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> arrayList = new ArrayList(); if (root == null) { return arrayList; } arrayList.add(root.val); printFromTopToBottom(root.left, root.right, arrayList); return arrayList; } private void printFromTopToBottom(TreeNode left, TreeNode right, ArrayList<Integer> arrayList) { if (left == null && right == null) { return; } if (left != null) { arrayList.add(left.val); } if (right != null) { arrayList.add(right.val); } if (left!=null){ printFromTopToBottom(left.left, left.right, arrayList); } if (right != null){ printFromTopToBottom(right.left, right.right, arrayList); } } }
Linux等环境软件安装
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步