fix(pkg): amend tree node

This commit is contained in:
reanon 2022-11-26 11:11:40 +08:00
parent 43e65b379d
commit fae6c6ac5b
2 changed files with 13 additions and 7 deletions

View File

@ -9,6 +9,9 @@ import (
"fmt" "fmt"
) )
// nodeNotExist represents node don't exist.
const nodeNotExist int = -1
type TreeNode struct { type TreeNode struct {
Val int Val int
Left *TreeNode Left *TreeNode
@ -55,7 +58,7 @@ func TreeToArray(root *TreeNode) []int {
if root == nil { if root == nil {
return []int{} return []int{}
} }
arr := make([]int, 16) arr := make([]int, 0)
queue := list.New() queue := list.New()
queue.PushBack(root) queue.PushBack(root)
for queue.Len() > 0 { for queue.Len() > 0 {
@ -65,7 +68,7 @@ func TreeToArray(root *TreeNode) []int {
queue.PushBack(node.Left) queue.PushBack(node.Left)
queue.PushBack(node.Right) queue.PushBack(node.Right)
} else { } else {
arr = append(arr, -1) arr = append(arr, nodeNotExist)
} }
} }
return arr return arr
@ -73,19 +76,19 @@ func TreeToArray(root *TreeNode) []int {
// PrintTree Print a binary tree // PrintTree Print a binary tree
func PrintTree(root *TreeNode) { func PrintTree(root *TreeNode) {
PrintTreeHelper(root, nil, false) printTreeHelper(root, nil, false)
} }
// PrintTreeHelper Help to print a binary tree, hide more details // printTreeHelper Help to print a binary tree, hide more details
// This tree printer is borrowed from TECHIE DELIGHT // This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/ // https://www.techiedelight.com/c-program-print-binary-tree/
func PrintTreeHelper(root *TreeNode, prev *trunk, isLeft bool) { func printTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
if root == nil { if root == nil {
return return
} }
prevStr := " " prevStr := " "
trunk := newTrunk(prev, prevStr) trunk := newTrunk(prev, prevStr)
PrintTreeHelper(root.Right, trunk, true) printTreeHelper(root.Right, trunk, true)
if prev == nil { if prev == nil {
trunk.str = "———" trunk.str = "———"
} else if isLeft { } else if isLeft {
@ -101,7 +104,7 @@ func PrintTreeHelper(root *TreeNode, prev *trunk, isLeft bool) {
prev.str = prevStr prev.str = prevStr
} }
trunk.str = " |" trunk.str = " |"
PrintTreeHelper(root.Left, trunk, false) printTreeHelper(root.Left, trunk, false)
} }
// trunk Help to Print tree structure // trunk Help to Print tree structure

View File

@ -12,4 +12,7 @@ func TestTreeNode(t *testing.T) {
// print tree // print tree
PrintTree(node) PrintTree(node)
// tree to arr
t.Log(TreeToArray(node))
} }