leetcode 655. 输出二叉树

  1. 题目链接 https://leetcode-cn.com/problems/print-binary-tree/submissions/

  2. 题目描述

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

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

      输入:
           1
          /
         2
      输出:
      [["", "1", ""],
       ["2", "", ""]]
      

      示例 2:

      输入:
           1
          / \
         2   3
          \
           4
      输出:
      [["", "", "", "1", "", "", ""],
       ["", "2", "", "", "", "3", ""],
       ["", "", "4", "", "", "", ""]]
      
  3. 解题思路

    1. 题目要求的二维数组行数为二叉树深度,列为pow(2, 深度) - 1
    2. 想构建一个上述大小的二维字符串数组。然后递归的填充即可。
  4. 代码

    1. python
      class Solution:
          def printTree(self, root: TreeNode) -> List[List[str]]:
              L = self._find(root)
              W = 2 ** L - 1
              ans = [[""] * W for _ in range(L)]
              
              def _draw(root, layer, left, right):
                  if not root:return 
                  nonlocal ans
                  mid = (left + right) // 2
                  ans[layer][mid] = str(root.val)
                  _draw(root.left, layer + 1, left, mid - 1)
                  _draw(root.right, layer + 1, mid + 1, right)
                  
              _draw(root, 0, 0, W - 1)
              return ans
              
              
          def _find(self, root):
              if not root: return 0;
              return max(self._find(root.left), self._find(root.right)) + 1
    2. c++
      class Solution {
      public:
          vector<vector<string>> printTree(TreeNode* root) {
              int D = find_depth(root);
              int W = pow(2, D) - 1;
              vector<vector<string>> ans(D, vector<string>(W, ""));        
              _helper(ans, root, 0, 0, W - 1);
              return ans;       
          }
          
          void _helper(vector<vector<string>>& ans, TreeNode* root,int n, int left, int right){
              if (not root)  return ;
              int mid = left + (right - left) / 2;
              ans[n][mid] = to_string(root->val);
              _helper(ans, root->left, n + 1, left, mid - 1);
              _helper(ans, root->right, n + 1, mid + 1, right);
          }
          int find_depth(TreeNode* root){
              if (not root) return 0;
              return max(find_depth(root->left), find_depth(root->right)) + 1;
          }
      };
      

猜你喜欢

转载自blog.csdn.net/qq_38043440/article/details/88615014