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

来源:互联网 发布:sql中replace的用法 编辑:程序博客网 时间:2024/05/16 19:00

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
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;    }}

奋斗
0 0
原创粉丝点击