其他分享
首页 > 其他分享> > Leetcode 655:输出二叉树

Leetcode 655:输出二叉树

作者:互联网

题目描述

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

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

示例 1:

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

示例 2:

输入:
     1
    / \
   2   3
    \
     4
输出:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

示例 3:

输入:
      1
     / \
    2   5
   / 
  3 
 / 
4 
输出:
[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

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

 

 

解题思路

class Solution {
public:
    int getHeight(TreeNode* root){
        if(root == NULL) return 0;
        int left = getHeight(root->left);
        int right = getHeight(root->right);
        return max(left,right)+1;
    }
    vector<vector<string>> printTree(TreeNode* root) {
        vector<vector<string>> ans;
        int h = getHeight(root);
        if(h == 0) return ans;
        ans = vector<vector<string>>(h,vector<string>(pow(2,h)-1));
        h-=1;
        int m = 1;
        ans[0][pow(2,h)-1] = to_string(root->val);
        queue<pair<TreeNode*,int>> que;
        que.push(make_pair(root,pow(2,h)-1));
        TreeNode *pre = root;
        while(!que.empty()){
            auto it = que.front().first;
            auto idx = que.front().second;
            que.pop();
            if(it->left != NULL){
                int tmp = idx - pow(2,h-m);
                ans[m][tmp] = to_string(it->left->val);
                que.push(make_pair(it->left,tmp));
            }
            if(it->right != NULL){
                int tmp = idx + pow(2,h-m);
                ans[m][tmp] = to_string(it->right->val);
                que.push(make_pair(it->right,tmp));
            }
            if(it == pre){
                pre = que.back().first;
                ++m;
            }
        }
        return ans;
    }
};

标签:tmp,right,int,655,que,二叉树,ans,root,Leetcode
来源: https://blog.csdn.net/weixin_35338624/article/details/100577934