Skip to content

Commit

Permalink
根到叶路径和
Browse files Browse the repository at this point in the history
  • Loading branch information
Azureki committed Apr 15, 2019
1 parent 599262e commit 8c2db95
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 1022. Sum of Root To Leaf Binary Numbers/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import "fmt"

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func dFS(root *TreeNode, base int) int {
if root == nil {
return 0
}
res := 0
base = (base << 1) + root.Val
if root.Left != nil {
res += dFS(root.Left, base)
}
if root.Right != nil {
res += dFS(root.Right, base)
}
if res != 0 {

return res
}
return base
}

func sumRootToLeaf(root *TreeNode) int {
return dFS(root, 0)
}

func main() {
root := TreeNode{1, nil, nil}
res := sumRootToLeaf(&root)
fmt.Println(res)
}

0 comments on commit 8c2db95

Please sign in to comment.