LeetCode算法第4篇:257Binary Tree Paths

来源:互联网 发布:电子采购软件 编辑:程序博客网 时间:2024/05/20 17:40

问题描述:
Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1 /   \2     3 \  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

代码实现:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; *//** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */char **findTreePath(struct TreeNode* root, int *returnSize);char** binaryTreePaths(struct TreeNode* root, int* returnSize) {    return findTreePath(root, returnSize);}char **findTreePath(struct TreeNode* root, int *returnSize){    char **pRightTree, **pLeftTree, **pReturn;    int i, rightSize, leftSize;    if (NULL == root)        return NULL;    if (NULL != root->right)    {        pReturn = findTreePath(root->right, returnSize);        pRightTree = (char **)malloc(sizeof(char *) * (*returnSize));        rightSize = *returnSize;        for (i = 0; i < (*returnSize); i++)        {            pRightTree[i] = (char *)malloc(sizeof(char) * (strlen(pReturn[i]) + 13) );            sprintf(pRightTree[i], "%d->%s", root->val, pReturn[i]);            free(pReturn[i]);        }        free(pReturn);    }    if (NULL != root->left)    {        pReturn = findTreePath(root->left, returnSize);        pLeftTree = (char **)malloc(sizeof(char *) * (*returnSize));        leftSize = *returnSize;        for (i = 0; i < (*returnSize); i++)        {            pLeftTree[i] = (char *)malloc(sizeof(char) * (strlen(pReturn[i]) + 13));            sprintf(pLeftTree[i], "%d->%s", root->val, pReturn[i]);            free(pReturn[i]);        }        free(pReturn);    }    if (NULL == root->right && NULL == root->left)    {        pLeftTree = (char **)malloc(sizeof(char *) * 1);        pLeftTree[0] = (char *)malloc(sizeof(char) * 12);        sprintf(pLeftTree[0], "%d", root->val);        *returnSize = 1;    } else {        if (NULL != root->left && NULL != root->right)        {            pLeftTree = (char **)realloc(pLeftTree, sizeof(char *) * (leftSize + rightSize));            memcpy(pLeftTree + leftSize, pRightTree, sizeof(char *) * rightSize);            free(pRightTree);            *returnSize = (leftSize + rightSize);        } else if (NULL == root->left){            pLeftTree = pRightTree;            *returnSize = rightSize;        } else {        }    }    return pLeftTree;}

总结:算法思路很简单,就是个二叉树的深度优先遍历,通过判断左右子树是否为空递归遍历。但用C语言实现算法存在大量的指针、指针的指针以及内存分配的操作,一不小心就会出现野指针和数组越界的问题。
  第一次运行的时候出现编译警告说findTreePath函数没有显示声明,将findTreePath函数在binaryTreePaths函数前声明一下后编译通过;第二次运行时出现Runtime Error,提示当输入为空树时输出错误,在25-26行加入空树判断;第三次运行时又出现Runtime Error,这次没了提示搞了半天没出来,转到IDE中自己建个样例试了一下发现输出结果时指针数组中的字符串出现顺序左右反了,回到代码一看原来在findTreePath函数第62-75行代码合并左右子树结果时将左子树的并到右子树后边去了,修改之后再次提交通过

0 0
原创粉丝点击