llllmz

导航

257. 二叉树的所有路径c

/**
 * 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 temp[200]={0};

void dfs(char** array,struct TreeNode* root,int* returnSize,int index){
    if(!root) return;
    if(!root->left&!root->right) {
        index+=sprintf(temp+index,"%d",root->val);
        array[*returnSize]=(char*)malloc(sizeof(char)*(index+5));
        for(int i=0;i<index;i++) array[*returnSize][i]=temp[i];
        array[*returnSize][index]=0;
        (*returnSize)++;
    }else{
        index+=sprintf(temp+index,"%d->",root->val);
        dfs(array,root->left,returnSize,index);
        dfs(array,root->right,returnSize,index);
    }
}

char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
    *returnSize=0;
    for(int i=0;i<200;i++) temp[i]=0;
    char** array=(char**)malloc(sizeof(char*)*200);
    dfs(array,root,returnSize,0);
    return array;
}

結果:

posted on 2024-03-14 13:32  神奇的萝卜丝  阅读(17)  评论(0)    收藏  举报