Print Binary Tree问题及解法

来源:互联网 发布:php 单例模式 编辑:程序博客网 时间:2024/05/18 17:01

问题描述:

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.

示例:

Input:     1    /   2Output:[["", "1", ""], ["2", "", ""]]
Input:     1    / \   2   3    \     4Output:[["", "", "", "1", "", "", ""], ["", "2", "", "", "", "3", ""], ["", "", "4", "", "", "", ""]]
Input:      1     / \    2   5   /   3  / 4 Output:[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""] ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""] ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""] ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

Note: The height of binary tree is in the range of [1, 10].

问题分析:

先求出树的高度,然后构造初始的m*n矩阵,再次遍历树,将节点值赋予到数组中去。


过程详见代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:   vector<vector<string>> printTree(TreeNode* root) {int maxDepth = 0;bl(root, 1, maxDepth);vector<vector<string>> res(maxDepth, vector<string>((int)pow(2, maxDepth) - 1, ""));if (res.size() > 0)bl2(res, root, 0, res[0].size() - 1, 1);return res;}void bl(TreeNode* root, int depth, int& maxDepth){if (root == nullptr) return;maxDepth = max(depth,maxDepth);bl( root->left, depth + 1, maxDepth);bl( root->right, depth + 1, maxDepth);}void bl2(vector<vector<string>>& res,TreeNode* root,int i ,int j,int depth){if (root == nullptr) return;res[depth - 1][(i + j) / 2] = to_string(root->val);bl2(res, root->left, i, (i + j) / 2 - 1, depth + 1);bl2(res, root->right, (i + j) / 2 + 1, j, depth + 1);}};