您的位置:首页 > 其它

606. Construct String from Binary Tree

2018-02-12 11:00 274 查看
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
Example 2:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example,
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
思路:主要是找到递归的顺序。首先我们要做的是先找出根结点值,我们找第一个左括号的位置,如果找不到,说明当前字符串都是数字,直接转化为整型,然后新建结点返回即可。否则的话从当前位置开始遍历,因为当前位置是一个左括号,我们的目标是找到与之对应的右括号的位置,但是由于中间还会遇到左右括号,所以我们需要用一个变量cnt来记录左括号的个数,如果遇到左括号,cnt自增1,如果遇到右括号,cnt自减1,这样当某个时刻cnt为0的时候,我们就确定了一个完整的子树的位置,那么问题来了,这个子树到底是左子树还是右子树呢,我们需要一个辅助变量start,当最开始找到第一个左括号的位置时,将start赋值为该位置,那么当cnt为0时,如果start还是原来的位置,说明这个是左子树,我们对其调用递归函数,注意此时更新start的位置,这样就能区分左右子树了,参见代码如下
代码1:/**
* 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) {
string s,temp,temp1;
if (!t) return "";
s = std::to_string(t->val);
if(t->left==NULL){
if(t->right==NULL){
return s;
}
else{
temp = tree2str(t->right);
s += "(";
s += ")";
s +="(";
s +=temp;
s +=")";
return s;
}
}
else{
if(t->right==NULL){
temp = tree2str(t->left);
s += "(" ;
s +=temp ;
s +=")" ;
return s;
}
else{
temp = tree2str(t->left);
temp1 = tree2str(t->right);
s += "(" ;
s += temp;
s += ")" ;
s += "(" ;
s += temp1;
s += ")" ;
return s;

}
}
}
};
代码2:/**
* 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) {
string res;
if(!t){return res;}
res += to_string(t->val);
if(t->left!=NULL){
res += "(";
res += tree2str(t->left);
res += ")";

}
else if(t->right!=NULL){res += "()";}

if(t->right!=NULL){
res += "(";
res += tree2str(t->right);
res += ")";
}
return res;
}

};
代码3:
class Solution {
public:
string tree2str(TreeNode* t) {
if (!t) return "";
string 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: