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().
 */
int temp[400];

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

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

 

posted on 2024-03-21 16:36  神奇的萝卜丝  阅读(1)  评论(0编辑  收藏  举报