JZ32 从上往下打印二叉树(简单)

描述

不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印。例如输入{8,6,10,#,#,2,1},如以下图中的示例二叉树,则依次打印8,6,10,2,1(空节点不打印,跳过),请你将打印的结果存放到一个数组里面,返回。

数据范围:

0<=节点总数<=1000

-1000<=节点值<=1000

示例1

输入:{8,6,10,#,#,2,1}

返回值:[8,6,10,2,1]

示例2

输入:{5,4,#,3,#,2,#,1}

返回值:[5,4,3,2,1]

解法:层次遍历、创建一个队列即可

import java.util.ArrayList;
import java.util.*;
/**
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> result = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        if(root == null){
            return result;
        }
        while(!queue.isEmpty()){
            TreeNode temp = queue.poll();
            int val = temp.val;
            result.add(temp.val);
            if(temp.left != null){
                queue.add(temp.left);
            }
            if(temp.right != null){
                queue.add(temp.right);
            }
        }
        return result;
        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47465999/article/details/121497077