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;
}