您的位置:首页 > 其它

Print Binary Tree问题及解法

2017-08-22 18:12 239 查看
问题描述:

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

The row number 
m
 should be equal to the height of the given binary tree.
The column number 
n
 should always be an odd number.
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.
Each unused space should contain an empty string 
""
.
Print the subtrees following the same rules.
示例:

Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]

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

Input:
1
/ \
2   5
/
3
/
4
Output:

[["",  "",  "", "",  "", "", "", "1", "",  ""
4000
,  "",  "",  "", "", ""]
["",  "",  "", "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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: