二叉树序列化反序列化

2022/9/16 23:47:12

本文主要是介绍二叉树序列化反序列化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Golang代码

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Treenode struct {
	Val         int
	Left, Right *Treenode
}

func Serialization(node *Treenode) string {
	if node == nil {
		return "nil"
	}
	tmp := []string{strconv.Itoa(node.Val)}
	tmp = append(tmp, Serialization(node.Left), Serialization(node.Right))
	return strings.Join(tmp, ",")
}

func Deserialize(s *[]string) *Treenode {
	if (*s)[0] == "nil" {
		*s = (*s)[1:]
		return nil
	}
	val, _ := strconv.Atoi((*s)[0])
	root := &Treenode{val, nil, nil}
	*s = (*s)[1:]
	if len(*s) > 0 {
		root.Left = Deserialize(s)
	}
	if len(*s) > 0 {
		root.Right = Deserialize(s)
	}
	return root
}

func main() {
	root := Treenode{2, nil, nil}
	root.Left = &Treenode{1, nil, nil}
	root.Right = &Treenode{3, nil, nil}

	res := Serialization(&root)
	fmt.Println(res) //2,1,nil,nil,3,nil,nil
	node_arr := strings.Split(res, ",")
	de_root := Deserialize(&node_arr)
	fmt.Println(de_root)
	fmt.Println(de_root.Left)
	fmt.Println(de_root.Right)

}



这篇关于二叉树序列化反序列化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程