dfs

  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 {number}
  12. */
  13. var sumNumbers = function(root) {
  14. if (!root) return root
  15. let arr = []
  16. let result = 0
  17. let dfs = (data, presum) => {
  18. if (data) {
  19. presum = data.val + presum * 10
  20. if (!data.left && !data.right)
  21. arr.push(presum)
  22. else {
  23. dfs(data.left, presum)
  24. dfs(data.right, presum)
  25. }
  26. }
  27. }
  28. dfs(root, 0)
  29. result = arr.reduce((a, b) => {return a + b})
  30. return result
  31. };

优化一下得到:

  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 {number}
  12. */
  13. var sumNumbers = function(root) {
  14. let dfs = (data, presum) => {
  15. if (data === null) return 0
  16. presum = data.val + presum * 10
  17. if (!data.left && !data.right) {
  18. return presum
  19. }
  20. return dfs(data.left, presum) + dfs(data.right, presum)
  21. }
  22. return dfs(root, 0)
  23. };

image.png