给定一个二叉树,返回所有从根节点到叶子节点的路径。
题目很短。
示例:
思路:
思路很简单,用DFS遍历所有节点,遇到子叶时,结束然后添加字符到输出中去。(一开始没有考虑到数字的位数和正负情况)
其余情况和**22.括号生成**类似(就是处理字符串数组的方式相同,而且都是用DFS进行遍历)。
代码:
// 将数字转换为字符(处理正负及多位字符)
void copyNum2Str (char* str, int temp, int* index)
{
int stack[10] = {0};
int top = 0;
if (temp < 0)
{
str[(*index) ++] = '-';
temp = - temp;
}
while (temp)
{
stack[top ++] = temp % 10;
temp = temp / 10;
}
while (top)
{
str[(*index) ++] = stack[--top] + '0';
}
return ;
}
//dfs遍历
void dfs (struct TreeNode* root, char* str, char** ans, int* returnSize, int index)
{
if (!root) return ;
if (!root->left && !root->right)// 该节点为子叶 终止递归
{
copyNum2Str(str, root->val, &index);
str[index] = '\0';
ans[(*returnSize)] = (char* )calloc(1000,sizeof(char));
strcpy(ans[(*returnSize)++], str);
return;
}
// 下面对当前节点惊进行输入 以及遍历左右儿子
copyNum2Str(str, root->val, &index);
str[index++] = '-';
str[index++] = '>';
dfs(root->left, str, ans, returnSize, index);
dfs(root->right, str, ans, returnSize, index);
}
char ** binaryTreePaths(struct TreeNode* root, int* returnSize)
{
//参数的初始化
*returnSize = 0;
if (!root) return NULL;
char* str = (char* )calloc(1000, sizeof(char));
char** ans = (char** )malloc(sizeof(char*) * 1000);
dfs(root, str, ans, returnSize, 0);
return ans;
}
注意点:
- str内存的申请用calloc,因为会将每一位初始化为’\0’,如果用malloc则没有初始化,在strcpy操作时会溢出(当然也可memset初始化什么的)。
- 别忘记处理正负号以及多位情况(重要的事情说三遍)。