一、题目
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
二、题目大意
找出所有根节点到叶子节点的路径。
三、解题思路
递归遍历二叉树。
四、代码实现
const binaryTreePaths = root => {
const ans = []
if (!root) {
return ans
}
help(root, String(root.val))
return ans
function help (root, str) {
if (!root.left && !root.right) {
ans.push(str)
return
}
if (root.left) {
help(root.left, str + '->' + root.left.val)
}
if (root.right) {
help(root.right, str + '->' + root.right.val)
}
}
}
如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

您还可以在这些地方找到我: