Leetcode Note: Go - Range Sum of BST

Range Sum of BST - LeetCode
https://leetcode.com/problems/range-sum-of-bst/

  • Go 言語で取り組んだメモ

回答

Go iterative (learning go for first time. Help to be more Golang-y?) - LeetCode Discuss
https://leetcode.com/problems/range-sum-of-bst/discuss/1344708/Go-iterative-(learning-go-for-first-time.-Help-to-be-more-Golang-y)

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func rangeSumBST(root *TreeNode, low int, high int) int {
	// You can clearly see I'm a Python head :D
	type Tuple struct {
		Root, Seen interface{}
	}
	rangeSum := 0
	nodesSeen := Tuple{root, false}
	stack := []Tuple{nodesSeen}

	for len(stack) != 0 {
		nodeSeen := stack[len(stack)-1]
		stack = stack[:len(stack)-1]

		node := nodeSeen.Root
		seen := nodeSeen.Seen

		if node.(*TreeNode) == nil {
			continue
		}
		if seen != true {
			stack = append(stack, 
							Tuple{node, true}, 
							Tuple{node.(*TreeNode).Left, false},
							Tuple{node.(*TreeNode).Right, false},  
						   )
		} else {
			val := node.(*TreeNode).Val
			fmt.Println(val)
			if val >= low && val <= high {
				rangeSum = rangeSum + val
			}
		}   
	}
	return rangeSum
}