二叉树序列化反序列化

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)

}

posted @   Notomato  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示