
这个题的要求就是打印一个二叉树,我们在此基础上进行修改,日后的二叉树问题,debug时就可以直接使用了,下面附上我的代码
/*
* @lc app=leetcode.cn id=655 lang=cpp
*
* [655] 输出二叉树
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
#include <vector>
#include <string>
#include <iostream>
using namespace std;
// @lc code=start
class Solution
{
int deep(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
int left = deep(root->left);
int right = deep(root->right);
return max(left, right) + 1;
}
void dfs(TreeNode *root, vector<vector<string>> &ret, int row, int col, const int &deep)
{
if (root == nullptr)
{
return;
}
ret[row][col] = to_string(root->val);
if (root->left != nullptr)
dfs(root->left, ret, row + 1, col - (1 << (deep - row - 1)), deep);
if (root->right != nullptr)
dfs(root->right, ret, row + 1, col + (1 << (deep - row - 1)), deep);
}
public:
vector<vector<string>> printTree(TreeNode *root)
{
int tree_deep = deep(root) - 1; // 根节点高度为0
int row = tree_deep + 1;
int col = (1 << row) - 1;
vector<vector<string>> ret(row, vector<string>(col, ""));
dfs(root, ret, 0, (col - 1) / 2, tree_deep);
for (int i = 0; i < ret.size(); i++)
{
for (int j = 0; j < ret[i].size(); j++)
{
cout << ret[i][j] << " ";
}
cout << endl;
}
return ret;
}
};
// @lc code=end
运行结果:


该代码实现了一个C++类Solution,用于按层序打印二叉树。通过深度优先搜索(DFS)策略,递归地处理左子树和右子树,并计算当前节点的层次。最后,将结果以二维字符串数组的形式返回并打印。
&spm=1001.2101.3001.5002&articleId=130925799&d=1&t=3&u=312f3afc40a9485fb9f566ec5d2ca64e)
422

被折叠的 条评论
为什么被折叠?



