leetcode 1022. Sum of Root To Leaf Binary Numbers

题解

前序遍历二叉树,通过左移运算符把遍历的二进制转化为十进制

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumRootToLeaf(root *TreeNode) int {
if root == nil {
return 0
}
return perTrav(root, 0)
}

func perTrav(root *TreeNode, cur int) int {
sum := 0
cur = cur << 1
cur += root.Val
if root.Left == nil && root.Right == nil {
sum += cur
return sum
}
if root.Left != nil {
sum += perTrav(root.Left, cur)
}
if root.Right != nil {
sum += perTrav(root.Right, cur)
}
return sum
}