来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。 叶子节点 是指没有子节点的节点。

解答

递归的思路,从根节点递归到最叶子节点,把路径在递归函数中带上
当既没有左子节点也没有右子节点时,收集路径

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} root
  11. * @return {string[]}
  12. */
  13. var binaryTreePaths = function(root) {
  14. const ret = [];
  15. function collect (node, path) {
  16. if (!node) return;
  17. path.push(node.val);
  18. if (!node.left && !node.right) {
  19. ret.push(path.join('->'));
  20. }
  21. node.left && collect(node.left, Array.from(path));
  22. node.right && collect(node.right, Array.from(path));
  23. }
  24. collect(root, []);
  25. return ret;
  26. };