题目

image.png
image.png

题解

  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 patharr = [];
  15. const dfs = (root, curpath) => {
  16. if(root.left === null && root.right === null) {
  17. curpath += root.val;
  18. patharr.push(curpath);
  19. return;
  20. };
  21. curpath += root.val + '->';
  22. root.left && dfs(root.left, curpath);
  23. root.right && dfs(root.right, curpath);
  24. }
  25. dfs(root, '')
  26. return patharr;
  27. };