MaxPathValueSearch is a method that searches the maximum path value in a tree given a certain depth
(deep int)
| 49 | // MaxPathValueSearch is a method that searches the maximum path value in a tree |
| 50 | // given a certain depth |
| 51 | func (r *Tree) MaxPathValueSearch(deep int) int { |
| 52 | if r.Root == nil { |
| 53 | return 0 |
| 54 | } |
| 55 | |
| 56 | type DFSNode struct { |
| 57 | Node Node |
| 58 | StepsLeft int |
| 59 | Sum int |
| 60 | } |
| 61 | |
| 62 | var pivot Node = r.Root |
| 63 | pivotEnded := false |
| 64 | maxPathValue := int(pivot.Value()) |
| 65 | |
| 66 | stack := make([]DFSNode, 0) |
| 67 | |
| 68 | for !pivotEnded { |
| 69 | stack = append(stack, DFSNode{Node: pivot, StepsLeft: deep, Sum: maxPathValue}) |
| 70 | |
| 71 | for len(stack) > 0 { |
| 72 | current := stack[len(stack)-1] |
| 73 | stack = stack[:len(stack)-1] |
| 74 | |
| 75 | // If we run out of steps, we check the sum of the path, |
| 76 | // update the maxPathValue if necessary and continue |
| 77 | if current.StepsLeft == 0 { |
| 78 | if current.Sum > maxPathValue { |
| 79 | maxPathValue = current.Sum |
| 80 | pivot = current.Node |
| 81 | } |
| 82 | continue |
| 83 | } |
| 84 | |
| 85 | if !current.Node.RightIsNil() { |
| 86 | stack = append(stack, DFSNode{ |
| 87 | Node: current.Node.Right(), |
| 88 | StepsLeft: current.StepsLeft - 1, |
| 89 | Sum: current.Sum + int(current.Node.Right().Value()), |
| 90 | }) |
| 91 | } |
| 92 | |
| 93 | // If the left child is nil, we have reached the end of the path |
| 94 | if !current.Node.LeftIsNil() { |
| 95 | stack = append(stack, DFSNode{ |
| 96 | Node: current.Node.Left(), |
| 97 | StepsLeft: current.StepsLeft - 1, |
| 98 | Sum: current.Sum + int(current.Node.Left().Value()), |
| 99 | }) |
| 100 | } else { |
| 101 | if current.Sum > maxPathValue { |
| 102 | maxPathValue = current.Sum |
| 103 | pivot = current.Node |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // If we don't have reached the end of the left side of the tree, |