题解 | #序列化二叉树#

序列化二叉树

https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84

package main

import (
	. "nc_tools"
	"strconv"
	"strings"
)

/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param root TreeNode类
 * @return TreeNode类
 */
func Serialize( root *TreeNode ) string {
    // write code here
    if root == nil {
        return ""
    }
    queue := []*TreeNode{root}
    result := []string{}
    for len(queue) > 0 {
        node := queue[0]
        queue = queue[1:]
        if node != nil {
            result = append(result, strconv.Itoa(node.Val))
            queue = append(queue, node.Left)
            queue = append(queue, node.Right)
        }else{
            result =append(result,  "#")        
        }
    }
    return strings.Join(result, ",")
}
func Deserialize( s string ) *TreeNode {
    // write code here
    if len(s) == 0 {
        return nil
    }
    results := strings.Split(s, ",")
    num,_ := strconv.Atoi(results[0])
    root := &TreeNode{Val: num}
    stack := []*TreeNode{root}
    index := 1
    for len(stack) > 0 {
        node := stack[0]
        stack = stack[1:]
        
        if index < len(results) && results[index] != "#" {
            curr,_ := strconv.Atoi(results[index])
            node.Left = &TreeNode{Val: curr}
            stack = append(stack, node.Left)
        }
        index++
        if index < len(results) && results[index] != "#" {
            curr,_ := strconv.Atoi(results[index])
            node.Right = &TreeNode{Val: curr}
            stack = append(stack, node.Right)
        }
        index++
    } 
    return root


}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务