【树4】从上往下打印二叉树

    xiaoxiao2026-09-30  12

    题目描述

    从上往下打印出二叉树的每个节点,同层节点从左至右打印。 import java.util.ArrayList; /** 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> list=new ArrayList<Integer>(); ArrayList<TreeNode> nodeList=new ArrayList<TreeNode>(); if(root==null) return list; int index=1; nodeList.add(root); while(nodeList.size()>0){ TreeNode temp=nodeList.remove(0); index--; //相当于打印 list.add(temp.val); //结点有左孩子 if(temp.left!=null) nodeList.add(index++,temp.left); //结点有右孩子 if(temp.right!=null) nodeList.add(index++,temp.right); } return list; } }
    转载请注明原文地址: https://ju.6miu.com/read-1312481.html
    最新回复(0)