2023-9-29 JZ32 从上往下打印二叉树

题目链接:从上往下打印二叉树

2023-9-29 JZ32 从上往下打印二叉树_第1张图片

import java.util.*;
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> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while(q.size() > 0){
            TreeNode t = q.peek();
            q.poll();
            res.add(t.val);
            if(t.left != null) q.add(t.left);
            if(t.right != null) q.add(t.right);
        }
        return res;
    }
}

你可能感兴趣的:(剑指offer,树,算法)