LeetCode257题-二叉树的所有路径

    具体题目去看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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值