left);strcat(s...">
美文网首页
606. Construct String from Binar

606. Construct String from Binar

作者: larrymusk | 来源:发表于2017-11-21 14:09 被阅读0次

先序遍历的同时,保存结果
遍历左子树
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;
}

相关文章

网友评论

      本文标题:606. Construct String from Binar

      本文链接:https://www.haomeiwen.com/subject/olzbvxtx.html