二叉树的所有路径
来源:力扣(leetcode)链接:https://leetcode.cn/problems/binary-tree-paths
题目:给你一个二叉树的根节点root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
e.g.
输入:root = [1,2,3,null,5]
输出:[1->2->5,1->3]
示例 2:
输入:root = [1]
输出:[1]
提示:
-100 <= node.val left == null && root->right == null) { // 当前节点是叶子节点
char* tmp = (char*)malloc(1001);
int len = 0;
for (int i = 0; i , sta[i]);
}
sprintf(tmp + len, %d, root->val);
res[(*returnsize)++] = tmp; // 把路径加入到答案中
} else {
sta[top++] = root->val; // 当前节点不是叶子节点,继续递归遍历
construct_paths(root->left, res, returnsize, sta, top);
construct_paths(root->right, res, returnsize, sta, top);
}
}
}
char** binarytreepaths(struct treenode* root, int* returnsize) {
char** paths = (char**)malloc(sizeof(char*) * 1001);
*returnsize = 0;
int sta[1001];
construct_paths(root, paths, returnsize, sta, 0);
return paths;
}
方法二:广度优先
/**
* note: the returned array must be malloced, assume caller calls free().
*/
char **binarytreepaths(struct treenode *root, int *returnsize) {
char **paths = (char **) malloc(sizeof(char *) * 1001);
*returnsize = 0;
if (root == null) {
return paths;
}
struct treenode **node_queue = (struct treenode **) malloc(sizeof(struct treenode *) * 1001);
char **path_queue = (char **) malloc(sizeof(char *) * 1001);
int left = 0, right = 0;
char *tmp = malloc(sizeof(char) * 1001);
sprintf(tmp, %d, root->val);
node_queue[right] = root;
path_queue[right++] = tmp;
while (left left == null && node->right == null) {
paths[(*returnsize)++] = path;
} else {
if (node->left != null) {
tmp = malloc(sizeof(char) * 1001);
sprintf(tmp, %s->%d, path, node->left->val);
node_queue[right] = node->left;
path_queue[right++] = tmp;
}
if (node->right != null) {
tmp = malloc(sizeof(char) * 1001);
sprintf(tmp, %s->%d, path, node->right->val);
node_queue[right] = node->right;
path_queue[right++] = tmp;
}
}
}
return paths;
}
艾迈斯半导体推出工作范围得到扩展、体积更小的dToF模块
Java初学者教学
纯电动汽车它在市场中的竞争优势是什么
燃气热水器使用方法 燃气热水器的升数大小有什么区别
什么样子的物联网架构才是合适的
二叉树按任意顺序,返回所有路径程序实现
基于DSP和X5165芯片的非易失性数据存储设计
基于LM12CLK的100W音频放大器电路图
笔记本和台式机处理器差在哪 笔记本最常见的处理器都有哪些?
2021曙光区块链存储系统强势来袭
5G到底绿色吗?辐射很大?耗电很高?
华为P10价格配置全曝光,P10 Plus 6GB+128GB售价超5千,你会买吗?
美政府:华为禁令至少持续5年
!租售/收购/维修HP8595E频谱分析仪HP8595E 小
万物互联时代我们需要怎样的智能连接设计
iPhone SE2的消息又双叒来了,你还相信吗?
电力监控系统的主要功能 电力系统的主要作用
数字化成汽车零部件发展趋势,数商云SRM系统库存管理模块助力企业转型升级
华为HMS Core 5.0上线,服务能力开放可覆盖七大领域
AI实现拐角处的实时汽车成像有什么意义