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 32 33 34 35 36 37 38 39 40 41 42 43 44
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func replaceValueInTree(root *TreeNode) *TreeNode { root.Val = 0 queue := []*TreeNode{root} for len(queue) > 0 { sonSum := 0 for _, node := range queue { if node.Left != nil { sonSum += node.Left.Val } if node.Right != nil { sonSum += node.Right.Val } } size := len(queue) for _, node := range queue[:size] { curSonSum := 0 if node.Left != nil { curSonSum += node.Left.Val } if node.Right != nil { curSonSum += node.Right.Val } curSonVal := sonSum - curSonSum if node.Left != nil { node.Left.Val = curSonVal queue = append(queue, node.Left) } if node.Right != nil { node.Right.Val = curSonVal queue = append(queue, node.Right) } } queue = queue[size:] } return root }
|