forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path257_binary_tree_paths.c
More file actions
66 lines (58 loc) · 1.51 KB
/
257_binary_tree_paths.c
File metadata and controls
66 lines (58 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Description : Binary Tree Paths
* Given a binary tree, return all root-to-leaf paths.
* Author : Evan Lau
* Date : 2016/05/12
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
char** binaryTreePaths(struct TreeNode* root, int* returnSize)
{
int leftSize = 0;
int rightSize = 0;
char **ret = NULL;
char **leftRet = NULL;
char **rightRet = NULL;
if (root == NULL)
{
*returnSize = 0;
return NULL;
}
if (root->left == NULL && root->right == NULL)
{
*returnSize = 1;
ret = (char **)malloc(sizeof(char *));
ret[0] = (char *)malloc(sizeof(char) * 16);
sprintf(ret[0], "%d", root->val);
return ret;
}
if (root->left != NULL)
{
leftRet = binaryTreePaths(root->left, &leftSize);
}
if (root->right != NULL)
{
rightRet = binaryTreePaths(root->right, &rightSize);
}
*returnSize = leftSize + rightSize;
ret = (char **)malloc(sizeof(char *) * *returnSize);
for (int i = 0; i < leftSize; i++)
{
ret[i] = (char *)malloc(sizeof(char) * 256);
sprintf(ret[i], "%d->", root->val);
strcat(ret[i], leftRet[i]);
}
for (int i = leftSize; i < *returnSize; i++)
{
ret[i] = (char *)malloc(sizeof(char) * 256);
sprintf(ret[i], "%d->", root->val);
strcat(ret[i], rightRet[i - leftSize]);
}
return ret;
}