From fae6c6ac5b8b491abead0d642bbbd6a98fa18487 Mon Sep 17 00:00:00 2001 From: reanon <793584285@qq.com> Date: Sat, 26 Nov 2022 11:11:40 +0800 Subject: [PATCH] fix(pkg): amend tree node --- codes/go/pkg/tree_node.go | 17 ++++++++++------- codes/go/pkg/tree_node_test.go | 3 +++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/codes/go/pkg/tree_node.go b/codes/go/pkg/tree_node.go index 571dfac..6175688 100644 --- a/codes/go/pkg/tree_node.go +++ b/codes/go/pkg/tree_node.go @@ -9,6 +9,9 @@ import ( "fmt" ) +// nodeNotExist represents node don't exist. +const nodeNotExist int = -1 + type TreeNode struct { Val int Left *TreeNode @@ -55,7 +58,7 @@ func TreeToArray(root *TreeNode) []int { if root == nil { return []int{} } - arr := make([]int, 16) + arr := make([]int, 0) queue := list.New() queue.PushBack(root) for queue.Len() > 0 { @@ -65,7 +68,7 @@ func TreeToArray(root *TreeNode) []int { queue.PushBack(node.Left) queue.PushBack(node.Right) } else { - arr = append(arr, -1) + arr = append(arr, nodeNotExist) } } return arr @@ -73,19 +76,19 @@ func TreeToArray(root *TreeNode) []int { // PrintTree Print a binary tree 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 // 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 { return } prevStr := " " trunk := newTrunk(prev, prevStr) - PrintTreeHelper(root.Right, trunk, true) + printTreeHelper(root.Right, trunk, true) if prev == nil { trunk.str = "———" } else if isLeft { @@ -101,7 +104,7 @@ func PrintTreeHelper(root *TreeNode, prev *trunk, isLeft bool) { prev.str = prevStr } trunk.str = " |" - PrintTreeHelper(root.Left, trunk, false) + printTreeHelper(root.Left, trunk, false) } // trunk Help to Print tree structure diff --git a/codes/go/pkg/tree_node_test.go b/codes/go/pkg/tree_node_test.go index c761ecb..ffbdf6f 100644 --- a/codes/go/pkg/tree_node_test.go +++ b/codes/go/pkg/tree_node_test.go @@ -12,4 +12,7 @@ func TestTreeNode(t *testing.T) { // print tree PrintTree(node) + + // tree to arr + t.Log(TreeToArray(node)) }