advent-of-code/hacker-rank/tree-preorder-traversal/main.go

53 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-04-05 16:27:02 -06:00
package main
import "fmt"
import "os"
import "bufio"
import "strconv"
import "strings"
func main() {
2024-10-26 12:03:06 -06:00
var length int
2024-04-05 16:27:02 -06:00
var tree *node
2024-10-26 12:03:06 -06:00
scanner := bufio.NewScanner(os.Stdin)
2024-04-05 16:27:02 -06:00
for scanner.Scan() {
2024-10-26 12:03:06 -06:00
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 {
2024-04-05 16:27:02 -06:00
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 "" }
2024-10-26 12:03:06 -06:00
return fmt.Sprintf("%v %v%v", n.value, n.left.String(), n.right.String())
2024-04-05 16:27:02 -06:00
2024-10-26 12:03:06 -06:00
}