题目:257. 二叉树的所有路径
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
搜索到某个节点时,若不为叶子节点,则继续查找下去。 当找到叶子节点时,将路径插入到最终结果中。
代码
class Solution {
public:
vector
<string
> binaryTreePaths(TreeNode
* root
) {
vector
<string
> ans
;
dfs(root
, "", ans
);
return ans
;
}
void dfs(TreeNode
* node
, string path
, vector
<string
>& ans
) {
if (node
== nullptr) {
return;
}
if (path
.empty()) {
path
= to_string(node
->val
);
} else {
path
+= "->" + to_string(node
->val
);
}
if (!node
->left
and !node
->right
) {
ans
.push_back(path
);
return;
}
dfs(node
->left
, path
, ans
);
dfs(node
->right
, path
, ans
);
}
};