Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Created April 15, 2024 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/25fef4daf1b89afd10e815de80b2b74a to your computer and use it in GitHub Desktop.
Save lbvf50mobile/25fef4daf1b89afd10e815de80b2b74a to your computer and use it in GitHub Desktop.
Leetcode: 129. Sum Root to Leaf Numbers.
// Leetcode: 129. Sum Root to Leaf Numbers.
// https://leetcode.com/problems/sum-root-to-leaf-numbers/
// = = = = = = = = = = = = = =
// Accepted.
// Thanks God, Jesus Christ!
// = = = = = = = = = = = = = =
// Runtime: 0 ms, faster than 100.00% of Go online submissions for Sum Root to
// Leaf Numbers.
// Memory Usage: 2.4 MB, less than 6.15% of Go online submissions for Sum Root
// to Leaf Numbers.
// 2024.04.15 Daily Challenge.
package main
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumNumbers(root *TreeNode) int {
// Number goes down, sum goes up.
// DFS is used.
return dfs(root, 0)
}
func dfs(x *TreeNode, val int) int {
if nil == x {
return 0
}
val = val*10 + x.Val
ans := 0
if nil == x.Left && nil == x.Right {
return val
} else {
ans += dfs(x.Left, val) + dfs(x.Right, val)
}
return ans
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment