Files
hello-algo/en/codes/go/pkg/tree_node.go
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

79 lines
1.8 KiB
Go

// File: tree_node.go
// Created Time: 2022-11-25
// Author: Reanon (793584285@qq.com)
package pkg
// TreeNode represents a binary tree node.
type TreeNode struct {
Val any // Node value
Height int // Node height
Left *TreeNode // Reference to the left child
Right *TreeNode // Reference to the right child
}
// NewTreeNode constructs a binary tree node.
func NewTreeNode(v any) *TreeNode {
return &TreeNode{
Val: v,
Height: 0,
Left: nil,
Right: nil,
}
}
// For the serialization rules, see:
// https://www.hello-algo.com/en/chapter_tree/array_representation_of_tree/
// Array representation of the binary tree:
// [1, 2, 3, 4, nil, 6, 7, 8, 9, nil, nil, 12, nil, nil, 15]
// Linked representation of the binary tree:
//
// /——— 15
// /——— 7
// /——— 3
// | \——— 6
// | \——— 12
//
// ——— 1
//
// \——— 2
// | /——— 9
// \——— 4
// \——— 8
// SliceToTreeDFS recursively deserializes a slice into a binary tree.
func SliceToTreeDFS(arr []any, i int) *TreeNode {
if i < 0 || i >= len(arr) || arr[i] == nil {
return nil
}
root := NewTreeNode(arr[i])
root.Left = SliceToTreeDFS(arr, 2*i+1)
root.Right = SliceToTreeDFS(arr, 2*i+2)
return root
}
// SliceToTree deserializes a slice into a binary tree.
func SliceToTree(arr []any) *TreeNode {
return SliceToTreeDFS(arr, 0)
}
// TreeToSliceDFS recursively serializes a binary tree into a slice.
func TreeToSliceDFS(root *TreeNode, i int, res *[]any) {
if root == nil {
return
}
for i >= len(*res) {
*res = append(*res, nil)
}
(*res)[i] = root.Val
TreeToSliceDFS(root.Left, 2*i+1, res)
TreeToSliceDFS(root.Right, 2*i+2, res)
}
// TreeToSlice serializes a binary tree into a slice.
func TreeToSlice(root *TreeNode) []any {
var res []any
TreeToSliceDFS(root, 0, &res)
return res
}