advent-of-code/hacker-rank/tree-preorder-traversal/main.go
xuu 04bbac8559
Some checks failed
Go Bump / bump (push) Failing after 6s
Go Test / build (push) Successful in 47s
chore: add hackerrank solutions
2024-10-26 12:03:06 -06:00

53 lines
1.1 KiB
Go

package main
import "fmt"
import "os"
import "bufio"
import "strconv"
import "strings"
func main() {
var length int
var tree *node
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
if length == 0 {
length, _ = strconv.Atoi(scanner.Text())
continue
}
for i, txt := range strings.Fields(scanner.Text()) {
if i >= length { break }
if v, err := strconv.Atoi(txt); err == nil {
tree = insert(tree, &node{value: v})
}
}
}
fmt.Println(tree)
}
type node struct {
value int
left *node
right *node
}
func insert(root, n *node) *node {
if root == nil {
return n
}
if root.value > n.value {
root.left = insert(root.left, n)
return root
}
root.right = insert(root.right, n)
return root
}
func (n *node) String() string {
if n == nil { return "" }
return fmt.Sprintf("%v %v%v", n.value, n.left.String(), n.right.String())
}