Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
webVueBlog opened this issue May 29, 2022 · 1 comment
Open

Comments

@webVueBlog
Copy link
Collaborator

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

@webVueBlog
Copy link
Collaborator Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant