具体题目去看LeetCode 257。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int g_listLength;
#define nullptr 0L
void GetPath (struct TreeNode* root, char **treePathList, char *nodeString,
int nodeStringLen)
{
int i;
char temp[100];
if (root == nullptr) {
return;
}
sprintf(temp, "%d", root->val);
for (i = 0; temp[i] != '\0'; i++) {
nodeString[nodeStringLen++] = temp[i];
}
nodeString[nodeStringLen] = '\0';
if (root->left == nullptr && root->right == nullptr) {
for (i = 0; nodeString[i] != '\0'; i++) { //error:居然想省略最后添加'\0',而用nodeString[i-1] != '\0'判断
treePathList[g_listLength][i] = nodeString[i];
}
treePathList[g_listLength][i] = '\0';
g_listLength++;
return;
}
nodeString[nodeStringLen++] = '-';
nodeString[nodeStringLen++] = '>';
if (root->left != nullptr) {
GetPath(root->left, treePathList, nodeString, nodeStringLen);
}
if (root->right != nullptr) {
GetPath(root->right, treePathList, nodeString, nodeStringLen);
}
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** binaryTreePaths(struct TreeNode* root, int* returnSize){
char **treePathList = (char **)malloc(sizeof(char *) * 100);
int i;
for (i=0; i<100; i++) {
treePathList[i] = (char *)malloc(sizeof(char) * 100);
}
char *nodeString = (char *)malloc(sizeof(char) * 100);
g_listLength = 0;
GetPath(root, treePathList, nodeString, 0);
*returnSize = g_listLength;
return treePathList;
}
具体代码如上所示。
学会了三件东西:
1)#define nullptr 0L
2)使用sprintf(string, "%d", num);把num转化为字符串。
3)malloc二维数组:
先malloc char**,即(char **)malloc(sizeof(char *) * num)
再malloc char*,即(char *)malloc(sizeof(char) * num)