nice-people-frontend-community / nice-js-leetcode

好青年 | leetcode 今日事今日毕(✅ Solutions to LeetCode by JavaScript, 100% test coverage, runtime beats 100% / LeetCode 题解 / GitHub Actions集成LeetCode每日一题至issues)
https://nice-people-frontend-community.github.io/nice-js-leetcode/
17 stars 1 forks source link

leetcode 129. 求根节点到叶节点数字之和 #回溯&树 #35

Open webVueBlog opened 2 years ago

webVueBlog commented 2 years ago

image 129. 求根节点到叶节点数字之和

webVueBlog commented 2 years ago

129. 求根节点到叶节点数字之和

/*
 * @lc app=leetcode.cn id=129 lang=javascript
 *
 * [129] 求根节点到叶节点数字之和
 */

// @lc code=start
/**
 * 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}

(56 ms)
 */
var sumNumbers = function(root) {
 let sum = 0
 const bst = (current, node) => {
  if(!node) return
  if(!node.left && !node.right) {
   sum += (current + node.val ) * 1;
   return
  }
  bst(current + node.val, node.left);
  bst(current + node.val, node.right);
 }
 bst('', root);
 return sum
}

// var sumNumbers = function(root) {
//  function traverse(node, num) {
//   if(!node) return null;
//   num += node.val
//   if(!node.left && !node.right) return +num;
//   return traverse(node.left, num) + traverse(node.right, num);
//  }
//  return traverse(root, '');
// };
// @lc code=end