zoukankan      html  css  js  c++  java
  • Leetcode 655.输出二叉树

    输出二叉树

    在一个 m*n 的二维字符串数组中输出二叉树,并遵守以下规则:

    1. 行数 m 应当等于给定二叉树的高度。
    2. 列数 n 应当总是奇数。
    3. 根节点的值(以字符串格式给出)应当放在可放置的第一行正中间。根节点所在的行与列会将剩余空间划分为两部分(左下部分和右下部分)。你应该将左子树输出在左下部分,右子树输出在右下部分。左下和右下部分应当有相同的大小。即使一个子树为空而另一个非空,你不需要为空的子树输出任何东西,但仍需要为另一个子树留出足够的空间。然而,如果两个子树都为空则不需要为它们留出任何空间。
    4. 每个未使用的空间应包含一个空的字符串""。
    5. 使用相同的规则输出子树。

    示例 1:

    输入:

    输出:

    [["", "1", ""],

    ["2", "", ""]]

    示例 2:

    输入:

    输出:

    [["", "", "", "1", "", "", ""],

    ["", "2", "", "", "", "3", ""],

    ["", "", "4", "", "", "", ""]]

    示例 3:

    输入:

    输出:

    [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]

    ["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]

    ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]

    ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]

    注意: 二叉树的高度在范围 [1, 10] 中。

     

     1 public class Solution {
     2     public List<List<String>> printTree(TreeNode root) {
     3         int height = getHeight(root);
     4         String[][] res = new String[height][(1 << height) - 1];
     5         for(String[] arr:res)
     6             Arrays.fill(arr,"");
     7         List<List<String>> ans = new ArrayList<>();
     8         fill(res, root, 0, 0, res[0].length);
     9         for(String[] arr:res)
    10             ans.add(Arrays.asList(arr));
    11         return ans;
    12     }
    13     public void fill(String[][] res, TreeNode root, int i, int l, int r) {
    14         if (root == null)
    15             return;
    16         res[i][(l + r) / 2] = "" + root.val;
    17         fill(res, root.left, i + 1, l, (l + r) / 2);
    18         fill(res, root.right, i + 1, (l + r + 1) / 2, r);
    19     }
    20     public int getHeight(TreeNode root) {
    21         if (root == null)
    22             return 0;
    23         return 1 + Math.max(getHeight(root.left), getHeight(root.right));
    24     }
    25 }

     

     

     

  • 相关阅读:
    Can't remove netstandard folder from output path (.net standard)
    website项目的reference问题
    The type exists in both DLLs
    git常用配置
    Map dependencies with code maps
    How to check HTML version of any website
    Bootstrap UI 编辑器
    网上职位要求对照
    Use of implicitly declared global variable
    ResolveUrl in external JavaScript file in asp.net project
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10394899.html
Copyright © 2011-2022 走看看