- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- 606. Construct String from Binar
- Leetcode PHP题解--D92 606. Constru
- 【1错-1】Construct String from Bina
- [LeetCode]606. Construct String
- 536. Construct Binary Tree from
先序遍历的同时,保存结果
遍历左子树
strcat(s,"(");
preorder(t->left);
strcat(s,")");
遍历右子树的时候,需要做个判断,是NULL就不需要遍历,避免出现(),这个是按照题意要求:
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.
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)".
if(t->right == NULL)
return ;
strcat(s,"(");
preorder(t->right);
strcat(s,")");
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
char *s = NULL;
void preorder(struct TreeNode *t){
if(t == NULL)
return;
char tmp[100];
sprintf(tmp, "%d", t->val);
strcat(s,tmp);
if(t->left == NULL && t->right == NULL)
return ;
strcat(s,"(");
preorder(t->left);
strcat(s,")");
if(t->right == NULL)
return ;
strcat(s,"(");
preorder(t->right);
strcat(s,")");
}
char* tree2str(struct TreeNode* t) {
s = calloc(100000, sizeof(char));
preorder(t);
return s;
}
网友评论