655. Print Binary Tree(打印二叉树)

题目描述

655. Print Binary Tree(打印二叉树)_第1张图片655. Print Binary Tree(打印二叉树)_第2张图片655. Print Binary Tree(打印二叉树)_第3张图片655. Print Binary Tree(打印二叉树)_第4张图片

方法思路

Recursive Solution

public class Solution {
    //Memory Usage: 37.8 MB, less than 5.71%
    //Runtime: 3 ms, faster than 100.00%
    public List<List<String>> printTree(TreeNode root) {
        int height = getHeight(root);
        String[][] res = new String[height][(1 << height) - 1];
        //<< 按位左移运算符。左操作数按位左移右操作数指定的位数
        for(String[] arr:res)
            Arrays.fill(arr,"");
        //将指定的String值分配给指定的String数组的每个元素
        List<List<String>> ans = new ArrayList<>();
        fill(res, root, 0, 0, res[0].length);
        for(String[] arr:res)
            ans.add(Arrays.asList(arr));
        //返回由指定数组支持的固定大小的列表
        return ans;
    }
    public void fill(String[][] res, TreeNode root, int i, int l, int r) {
        if (root == null)
            return;
        res[i][(l + r) / 2] = "" + root.val;
        fill(res, root.left, i + 1, l, (l + r) / 2);
        fill(res, root.right, i + 1, (l + r + 1) / 2, r);
    }
    public int getHeight(TreeNode root) {
        if (root == null)
            return 0;
        return 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
}

题目链接:

https://leetcode.com/problems/print-binary-tree/

你可能感兴趣的:(温故知新,Tree)