牛客网刷题(JAVA) 23:从上往下打印二叉树

难度系数 ⭐⭐

时间限制 C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目内容 从上往下打印出二叉树的每个节点,同层节点从左至右打印。

思路 设置一个队列,遍历树,初始将根节点加入到队列中。当队列非空时,将队头元素弹出,判断弹出元素是否有左、右孩子,若有,则将其加入队列(注意顺序)。循环至队列为空结束。

package nowcoder;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class No24 {
    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        if (root == null) return null;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode flag = queue.poll();
            res.add(flag.val);
            if (flag.left != null) queue.offer(flag.left);
            if (flag.right != null) queue.offer(flag.right);
        }
        return res;
    }

    public static void printTree(TreeNode head) {
        System.out.println("Binary Tree:");
        printInOrder(head, 0, "H", 17);
        System.out.println();
    }

    public static void printInOrder(TreeNode head, int height, String to, int len) {
        if (head == null) {
            return;
        }
        printInOrder(head.right, height + 1, "v", len);
        String val = to + head.val + to;
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(height * len) + val);
        printInOrder(head.left, height + 1, "^", len);
    }

    public static String getSpace(int num) {
        String space = " ";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            buf.append(space);
        }
        return buf.toString();
    }

    public static void main(String[] args){
        TreeNode head = new TreeNode(1);
        head.left = new TreeNode(2);
        head.right = new TreeNode(3);
        head.left.left = new TreeNode(4);
        head.right.left = new TreeNode(5);
        head.right.right = new TreeNode(6);
        head.left.left.right = new TreeNode(7);
        printTree(head);

        System.out.println();
        ArrayList<Integer> res = PrintFromTopToBottom(head);
        for (int i = 0; i < res.size(); i++)
            System.out.print(res.get(i) + " ");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值