257. Binary Tree Paths

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

Analyze

  • DFS 深度优先遍历的运用, 关键需要想清楚采用先序、中序、后序遍历中的哪一种。
    • 先序遍历: 1 -> 2 -> 5, 1 -> 3
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function(root) {
const result = []
if (!root) return result
printTreePaths(root, result, '')
return result
}
var printTreePaths = function(node, result, str) {
if (!node.left && !node.right) {
str += `${node.val}`
result.push(str)
return
}
str += `${node.val}->`
if (node.left) {
printTreePaths(node.left, result, str)
}
if (node.right) {
printTreePaths(node.right, result, str)
}
}