我在Go中实现了AVLTreeMap,但是将值作为指针传递给了我一些问题。我正在尝试更新节点指针的值,但该值在函数后将不会持久。
在函数 func(树* AVLTreeMap)中放置(键int,值字符串)。我能够修改树的根节点,并且可以在主目录中打印它。但是,当我将同一根传递给函数 func(节点* Node)insertByKey(键int,值字符串)之后,该值将不会更新,只有put()中的值会持续存在。
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"io"
)
/* NODE */
type Node struct {
key int
value string
left *Node
right *Node
height int
}
/* TREE */
type AVLTreeMap struct {
root *Node
}
func (tree *AVLTreeMap) get(key int) string {
value := tree.root.lookupByKey(key)
if value == "" {
return "Not Found"
}
return value
}
func (node *Node) inOrder() {
fmt.Println(node)
if (node != nil) {
fmt.Println(node.key)
node.left.inOrder()
node.inOrder()
node.right.inOrder()
}
}
func (node *Node) lookupByKey(key int) string {
if (node == nil) { // check for nullptr
return ""
} else if (node.key == key) { // key matching
return node.value
} else if (key < node.left.key) { // recur left
return node.left.lookupByKey(key)
} else if (key > node.right.key) { // recur right
return node.right.lookupByKey(key)
}
return ""
}
func (node *Node) insertByKey(key int, value string) {
if (node == nil) { // check for nullptr
node = &Node{ key: key, value: value,}
} else if (key < node.key) { // recur left
node.left.insertByKey(key, value)
} else if (key > node.key) { // recur right
node.right.insertByKey(key, value)
}
}
func (tree *AVLTreeMap) put(key int, value string) {
//fmt.Println(tree.root)
tree.root = &Node{ key: 1, value: "2",}
tree.root.insertByKey(key, value)
}
func (tree *AVLTreeMap) remove(key int) {
return
}
func (tree *AVLTreeMap) levelOrder() {
return
}
func (tree *AVLTreeMap) rotateLeft(curr *Node) *Node {
return curr
}
func (tree *AVLTreeMap) rotateRight(curr *Node) *Node {
return curr
}
func (tree *AVLTreeMap) getHeight(curr *Node) int {
return 1
}
func (tree *AVLTreeMap) getBalance(curr *Node) int {
return 1
}
/* UTILS */
func checkError(err error) {
if err != nil {
panic(err)
}
}
func strToInt(val string) int {
if val, err := strconv.Atoi(val); err == nil {
return val
}
return 0
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func getCommand(command string, tree *AVLTreeMap) {
vals := strings.Split(command, " ")
var (
key int
val string
)
if len(vals) == 1 { // level order
tree.levelOrder()
} else if len(vals) == 3 { // put
key, val = strToInt(vals[1]), vals[2]
tree.put(key, val)
} else if len(vals) == 2 { // get
//key = strToInt(vals[1])
//fmt.Println(tree.get(key))
}
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16 * 1024 * 1024)
// get num commands
numCommands := strToInt(readLine(reader))
fmt.Println(numCommands)
// initialize new TreeMap
tree := AVLTreeMap{}
//tree.root = &Node{ key: 1, value: "z", }
for {
val := readLine(reader)
if val == "" {
break;
} else {
// run commands on tree
getCommand(val, &tree)
}
}
fmt.Println(tree.root)
//tree.root.inOrder()
}