思路:用队列保存二叉树的层节点,不断地从中弹出节点。每一次都用新的temp变量保存当前层的第一个节点
import java.util.ArrayList; import java.util.LinkedList; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList<Integer> res = new ArrayList<Integer>(); if(root == null){ return res; } ArrayList<TreeNode> queue = new ArrayList<>(); queue.add(root); while(!queue.isEmpty()){ TreeNode temp = queue.remove(0); if(temp.left != null){ queue.add(temp.left); } if(temp.right != null){ queue.add(temp.right); } res.add(temp.val); } return res; } }
时间: 2024-11-03 16:11:02