655. Print Binary Tree**

本文详细解析了LeetCode上的第655题“Print Binary Tree”,探讨了如何将二叉树以二维字符串数组的形式进行打印,确保行数等于树的高度,列数为奇数,并保持根节点在每行正中间。提供了两种C++实现方法,一种通过递归,另一种采用层序遍历,同时强调了代码中易错点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

655. Print Binary Tree**

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

题目描述

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.
  2. The column number n should always be an odd number.
  3. The root node’s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don’t need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don’t need to leave space for both of them.
  4. Each unused space should contain an empty string "".
  5. Print the subtrees following the same rules.

C++ 实现 1

递归版本. 首先注意观察返回结果中, 矩阵大小 m * n 和树的高度 h 的关系. 其中 m = h, 而 n = 2^h - 1. 那么可以先确定树的高度, 得到矩阵的大小. 之后再确定树中每个节点的值在矩阵中的位置. 我不知道这里怎么清楚的描述, 任意以个节点处在两棵子树的中心位置. 用 leftright 来确定左右子树的范围, 用 mid = (left + right) / 2 来确定节点的位置. 在递归过程中, 维护 leftright.

class Solution {
private:
    int height(TreeNode *root) {
        if (!root) return 0;
        return std::max(height(root->left), height(root->right)) + 1;
    }
    void build(TreeNode *root, int row, int left, int right,
              vector<vector<string>> &res) {
        if (!root) return;
        int mid = left + (right - left) / 2;
        res[row][mid] = std::to_string(root->val);
        build(root->left, row + 1, left, mid - 1, res);
        build(root->right, row + 1, mid + 1, right, res);
    }
public:
    vector<vector<string>> printTree(TreeNode* root) {
        if (!root) return {};
        int layers = height(root);
        int cols = int(std::pow(2, layers)) - 1;
        vector<vector<string>> res(layers, vector<string>(cols, ""));
        int left = 0, right = cols - 1;
        build(root, 0, left, right, res);
        return res;
    }
};

C++ 实现 2

使用层序遍历也可以完成, 第一部仍然是求出树的高度. 在队列中维护节点本身以及它的左右范围.

class Solution {
private:
    int height(TreeNode *root) {
        if (!root) return 0;
        return std::max(height(root->left), height(root->right)) + 1;
    }
public:
    vector<vector<string>> printTree(TreeNode* root) {
        if (!root) return {};
        int layers = height(root);
        int cols = int(std::pow(2, layers)) - 1;
        vector<vector<string>> res(layers, vector<string>(cols, ""));
        int row = -1;
        queue<pair<TreeNode*, vector<int>>> q;
        q.push(make_pair(root, vector<int>{0, cols - 1}));
        while (!q.empty()) {
            auto size = q.size();
            row ++;
            while (size --) {
                auto p = q.front();
                q.pop();
                auto r = p.first;
                auto left = p.second[0];
                auto right = p.second[1];
                int mid = left + (right - left) / 2;
                res[row][mid] = std::to_string(r->val);
                if (r->left) 
                    q.push(make_pair(r->left, vector<int>{left, mid - 1}));
                if (r->right) 
                    q.push(make_pair(r->right, vector<int>{mid + 1, right}));
            }
        }
        return res;
    }
};

题外话, 如下作为警示, 写代码的时候, 把其中一段代码写成:

res[row][mid] = std::to_string(root->val);
if (root->left) 
    q.push(make_pair(root->left, vector<int>{left, mid - 1}));
if (root->right) 
    q.push(make_pair(root->right, vector<int>{mid + 1, right}));

查 bug 都查 🤮🤮🤮🤮🤮🤮, 才发现了原来是 r 写成了 root

# -*- coding: utf-8 -*- '''请在Begin-End之间补充代码, 完成BinaryTree类''' class BinaryTree: # 创建左右子树为空的根结点 def __init__(self, rootObj): self.key = rootObj # 成员key保存根结点数据项 self.leftChild = None # 成员leftChild初始化为空 self.rightChild = None # 成员rightChild初始化为空 # 把newNode插入到根的左子树 def insertLeft(self, newNode): if self.leftChild is None: self.leftChild = BinaryTree(newNode) # 左子树指向由newNode所生成的BinaryTree else: t = BinaryTree(newNode) # 创建一个BinaryTree类型的新结点t t.leftChild = self.leftChild # 新结点的左子树指向原来根的左子树 self.leftChild = t # 根结点的左子树指向结点t # 把newNode插入到根的右子树 def insertRight(self, newNode): if self.rightChild is None: # 右子树指向由newNode所生成的BinaryTree # ********** Begin ********** # self.rightChild = BinaryTree(newNode) # ********** End ********** # else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t # ********** End ********** # # 取得右子树,返回值是一个BinaryTree类型的对象 def getRightChild(self): # ********** Begin ********** # return self.rightChild # ********** End ********** # # 取得左子树 def getLeftChild(self): # ********** Begin ********** # return self.leftChild # ********** End ********** # # 设置根结点的值 def setRootVal(self, obj): # 将根结点的值赋值为obj # ********** Begin ********** # self.key = obj # ********** End ********** # # 取得根结点的值 def getRootVal(self): # ********** Begin ********** # return self.key # ********** End ********** # # 主程序 input_str = input() nodes = input_str.split(',') # 创建根节点 root = BinaryTree(nodes[0]) # 插入左子树和右子树 if len(nodes) > 1: root.insertLeft(nodes[1]) if len(nodes) > 2: root.insertRight(nodes[2]) # 前三行输出:对创建的二叉树按编号顺序输出结点 print(root.getRootVal()) left_child = root.getLeftChild
最新发布
03-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值