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 45 46 47 48
| /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func amountOfTime(root *TreeNode, start int) int { relations := make(map[int][]int) var searchParent func(cur, pre *TreeNode) searchParent = func(cur, pre *TreeNode) { list := []int{} if pre != nil { list = append(list, pre.Val) } if cur.Left != nil { list = append(list, cur.Left.Val) searchParent(cur.Left, cur) } if cur.Right != nil { list = append(list, cur.Right.Val) searchParent(cur.Right, cur) } relations[cur.Val] = list } searchParent(root, nil) queue := []int{start} visit := map[int]bool{start: true} ans := 0 for { size := len(queue) for i := 0; i < size; i++ { for _, nodeVal := range relations[queue[i]] { if !visit[nodeVal] { visit[nodeVal] = true queue = append(queue, nodeVal) } } } queue = queue[size:] if len(queue) == 0 { break } ans++ } return ans }
|