给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
- 树中节点的数目在范围
[1, 100]
内 -100 <= Node.val <= 100
这是一道常规 DFS 题,
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root) {
const paths = [];
function findAllPaths(node, path) {
if (!node) return;
const { val, left, right } = node;
path.push(val);
!left && !right && paths.push(path.join("->"));
findAllPaths(node.left, path);
findAllPaths(node.right, path);
path.pop();
}
findAllPaths(root, []);
return paths;
};
复杂度分析:
假设树节点数为 n。
时间复杂度:深度优先搜索中每个节点都会被访问一次,每一次花费 O(n) 时间去构建路径字符串。因此,时间复杂度为 \(O(n^2)\)。
空间复杂度:递归调用的层数最坏情况下为 n 层,每一层都有 path 变量,其耗费的空间为 \(O(\sum_{i=1}^n{i})=O(n^2)\)。