chore: add hackerrank solutions
This commit is contained in:
52
hacker-rank/tree-preorder-traversal/main.go
Normal file
52
hacker-rank/tree-preorder-traversal/main.go
Normal file
@@ -0,0 +1,52 @@
|
||||
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())
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user