LeetCode刷题测试辅助(更好的二叉树打印)

LeetCode刷题测试辅助(更好的二叉树打印)_第1张图片

这个题的要求就是打印一个二叉树,我们在此基础上进行修改,日后的二叉树问题,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 
#include 
#include 
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

运行结果:
LeetCode刷题测试辅助(更好的二叉树打印)_第2张图片
LeetCode刷题测试辅助(更好的二叉树打印)_第3张图片

你可能感兴趣的:(#,LeetCode,#,剑指offer,leetcode,深度优先,算法)