fix(pkg): amend tree node
This commit is contained in:
parent
43e65b379d
commit
fae6c6ac5b
@ -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
|
||||
|
@ -12,4 +12,7 @@ func TestTreeNode(t *testing.T) {
|
||||
|
||||
// print tree
|
||||
PrintTree(node)
|
||||
|
||||
// tree to arr
|
||||
t.Log(TreeToArray(node))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user