llllmz

导航

257. 二叉树的所有路径c

很好的题目,让我的sprintf旋转

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

char* change(int* stack,int top){
    char* t=(char*)malloc(sizeof(char)*100);
    int index=0;
    for(int i=0;i<top-1;i++){
        index+=sprintf(t+index,"%d->",stack[i]);
    }
    sprintf(t+index,"%d",stack[top-1]);
    return t;
}
  
void preorder(struct TreeNode* root,char** temp,int *returnSize,int* stack,int top){
    if(!root) return;
    if(!root->left&&!root->right){
        stack[top++]=root->val;
        char* x=change(stack,top);
        temp[(*returnSize)++]=x;
    }else{
        stack[top++]=root->val;
        preorder(root->left,temp,returnSize,stack,top);
        preorder(root->right,temp,returnSize,stack,top);
    }
}

char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
    *returnSize=0;   
    if(!root) return NULL;
    char** temp=(char**)malloc(sizeof(char*)*100);
    int stack[100]={0};
    int top=0;
    preorder(root,temp,returnSize,stack,top);
    return temp;
}

结果:

posted on 2024-03-05 20:34  神奇的萝卜丝  阅读(21)  评论(0)    收藏  举报