LeetCode606:Construct String from Binary Tree
题目大意
题目大意: 根据已给的二叉树,按照先序遍历的顺序生成字符串,利用()分开各个子树。
Example 1:
Input: Binary tree: [1,2,3,4] 1 / \ 2 3 / 4
Output: "1(2(4))(3)"
Example 2:
Input: Binary tree: [1,2,3,null,4] 1 / \ 2 3 \ 4
Output: "1(2()(4))(3)"
已给代码格式如下:
/**
* 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:
string tree2str(TreeNode* t) {
}
};
思路分析
分析题中所给例子可知:每个子树用()包含,如果一棵树的左子树为空,而右子树不为空,则用()表示空左子树。
因此,需要对二叉树的先序遍历进行条件选择,并将遍历结果加入结果字符串s中,遍历结束后输出。
可根据二叉树的先序遍历算法改进转化而得到,代码如下:
string tree2str(TreeNode* t) {
string s="";
if(t){
s = to_string(t->val);
if(t->left){
s += "("+ tree2str(t->left)+")";
}else if(t->right){
s += "()";
}
if(t->right){
s += "("+ tree2str(t->right)+")";
}
}
return s;
}
遇到的问题及解决方案
根据之前经验,将数字转化成字符串只需要在赋值时加上一个空字符串即可,形式如下:
int n = 5;
string s = "" +n;
即可获得s = "5";
但是在调试过程中发现,在LeetCode中并不能编译成功,需要用to_string()函数转化。