LeetCode - 655. Print Binary Tree(按照字符矩阵的形式打印二叉树)(二分和递归)

33 篇文章 0 订阅

LeetCode - 655. Print Binary Tree(按照字符矩阵的形式打印二叉树)(二分和递归)

题目链接
题目

在这里插入图片描述

解析

找出对应的下标,然后二分递归遍历填充,先求出高度h,然后求出宽度为w = 2h-1,然后填充一个hw列的字符矩阵即可,上下递归和左右二分夹杂在一起的感觉。具体看下图:
这里写图片描述

class Solution {

    private List<List<String>> res;

    public List<List<String>> printTree(TreeNode root) {
        res = new ArrayList<>();
        int h = height(root);
        int w = (1 << h) - 1;
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < w; i++) temp.add("");
        for (int i = 0; i < h; i++)
            res.add(new ArrayList<>(temp)); //这个不能直接写成temp必须要写成new ArrayList
        rec(root, 0, 0, w - 1); 
        return res;
    }

    public void rec(TreeNode root, int level, int l, int r) {
        if (root == null) return;
        int m = l + (r - l) / 2;
        res.get(level).set(m, String.valueOf(root.val));
        rec(root.left, level + 1, l, m - 1);
        rec(root.right, level + 1, m + 1, r);
    }
    
    public int height(TreeNode root) {
        if (root == null)
            return 0;
        return Math.max(height(root.left), height(root.right)) + 1;
    }
}

或者使用二维字符矩阵:

class Solution {

    private String[][] str;

    public List<List<String>> printTree(TreeNode root) {
        int height = height(root);
        str = new String[height][(1 << height) - 1];
        for (String[] arr : str)
            Arrays.fill(arr, "");

        rec(root, 0, 0, str[0].length);

        List<List<String>> res = new ArrayList<>();
        for (String[] arr : str)
            res.add(Arrays.asList(arr)); //asList()将一个数组转换成容器
        return res;
    }

    public void rec(TreeNode root, int level, int l, int r) {
        if (root == null)
            return;
        int m = l + (r - l) / 2;
        str[level][m] = "" + root.val;
        rec(root.left, level + 1, l, m - 1);
        rec(root.right, level + 1, m + 1, r);
    }

    public int height(TreeNode root) {
        if (root == null)
            return 0;
        return Math.max(height(root.left), height(root.right)) + 1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值