来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。 叶子节点 是指没有子节点的节点。
解答
递归的思路,从根节点递归到最叶子节点,把路径在递归函数中带上
当既没有左子节点也没有右子节点时,收集路径
/*** 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 ret = [];function collect (node, path) {if (!node) return;path.push(node.val);if (!node.left && !node.right) {ret.push(path.join('->'));}node.left && collect(node.left, Array.from(path));node.right && collect(node.right, Array.from(path));}collect(root, []);return ret;};
