LeetCode257. 二叉树的所有路径

https://leetcode-cn.com/problems/binary-tree-paths/

给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。

示例:
输入:
1
2 3
NULL NULL 5 NULL

输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

思路:这道题的关键点是如何实现深度优先搜索的同时,保存所遍历的节点,并在遍历到叶子节点的时候打印整条路径上的值。方法也很简单,利用path数组保存当前depth上的节点值。

/**
 * 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().
 */
void dfs(struct TreeNode* root, char **ret, int *returnSize, int *path, int depth){
    int i = 0;
    path[depth++] = root->val; // path数组保存遍历的节点
    // 到叶子节点时打印该路径
    if(root->left == NULL && root->right == NULL){
        ret[*returnSize] = (char *)calloc(1, sizeof(char) * 100);
        for(i = 0; i < depth - 1; i++){
            sprintf(ret[*returnSize], "%s%d->", ret[*returnSize], path[i]);
        } 
        sprintf(ret[*returnSize], "%s%d",ret[*returnSize],path[i]);
        (*returnSize)++;
        return;
    }
    if(root->left != NULL){
        dfs(root->left, ret, returnSize, path, depth);
    }
    if(root->right != NULL){
        dfs(root->right, ret, returnSize, path, depth);
    }
    return;
}

char** binaryTreePaths(struct TreeNode* root, int* returnSize) {
    int path[100] = {0};
    int depth = 0;
   
    char **ret = (char **)malloc(sizeof(char*) * 100);
    if(NULL == root){
        return root; // malloc 要放在返回之前,因为外面要free.
    }
    *returnSize = 0;
    dfs(root, ret, returnSize, path, depth);
    return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值