zoukankan      html  css  js  c++  java
  • leetcode 655. 输出二叉树 【时间击败100.00%】 【内存击败96.49%】

     1  public List<List<String>> printTree(TreeNode root) {
     2         ArrayList<List<String>> al = new ArrayList<>();
     3         if (root == null) return al;
     4         if (root.left == null && root.right == null) {
     5             al.add(new ArrayList<>());
     6             al.get(0).add(String.valueOf(root.val));
     7             return al;
     8         }
     9 
    10         int high = dep(root, 1);
    11         String[][] ans = new String[(int) Math.pow(2, high)][high + 1];
    12         add(root, (int) Math.pow(2, high - 1), 1, (int) Math.pow(2, high - 2), ans);
    13         for (int i = 1; i <= high; i++) {
    14             al.add(new ArrayList<>());
    15             for (int j = 1; j < ans.length; j++)
    16                 al.get(i - 1).add(ans[j][i] == null ? "" : ans[j][i]);
    17         }
    18         return al;
    19     }
    20 
    21     public void add(TreeNode cur, int x, int y, int diff, String[][] ans) {
    22         if (cur == null) return;
    23         ans[x][y] = cur.val + "";
    24         add(cur.left, x - diff, y + 1, diff / 2, ans);
    25         add(cur.right, x + diff, y + 1, diff / 2, ans);
    26     }
    27 
    28 
    29     public int dep(TreeNode cur, int dep) {
    30         if (cur == null) return dep - 1;
    31         return Math.max(dep(cur.left, dep + 1), dep(cur.right, dep + 1));
    32     }
  • 相关阅读:
    转载——rdis安装yum版本
    Lc28_strStr kmp字符串匹配
    关于 哈希的总结
    Lc344_反转字符串
    Lc383_赎金信
    Lc454_四数相加 II
    Lc1_俩数之和
    推荐4款个人珍藏的IDEA插件!帮你写出不那么差的代码
    ZUC-生成随机序列
    移位运算
  • 原文地址:https://www.cnblogs.com/towerbird/p/11583361.html
Copyright © 2011-2022 走看看