尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 297
已运行时间: 955

文章分类

目录
  1. dfs

尼采般地抒情

尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 297
已运行时间: 955

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 {number}
  _/
  var sumNumbers = function(root) {
  if (!root) return root
  let arr = []
  let result = 0
  let dfs = (data, presum) => {
  if (data) {
  presum = data.val + presum _ 10
  if (!data.left && !data.right)
  arr.push(presum)
  else {
  dfs(data.left, presum)
  dfs(data.right, presum)
  }
  }
  }
  dfs(root, 0)
  result = arr.reduce((a, b) => {return a + b})
  return result
  };

优化一下得到:

/\*\*
- 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 {number}
  _/
  var sumNumbers = function(root) {
  let dfs = (data, presum) => {
  if (data === null) return 0
  presum = data.val + presum _ 10
  if (!data.left && !data.right) {
  return presum
  }
  return dfs(data.left, presum) + dfs(data.right, presum)
  }
  return dfs(root, 0)
  };

评论区

Twikoo giscus

最新评论

Loading...