🌝

BinaryTree in Go

Posted at — Dec 27, 2020
#golang

Introduce how to create a binary-tree with go.

Create a binarytree by golang

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//TreeNode :
type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

//Create treenode by traversal
func createTree(lr string, d int, parent int) *TreeNode {
	var a string

	if lr == "root" {
		fmt.Printf("Please input the deep: %d %s node of root:\r\n", d, lr)
	} else {
		fmt.Printf("Please input the deep: %d %s node of node: %d:\r\n", d, lr, parent)
	}

	fmt.Scanln(&a)
	//Stop to creating the branch by typing '#'
	if a == "#" {
		fmt.Printf("Stop traversal on deep: %d\r\n", d)
		return nil
	}
	tree := new(TreeNode)
	tree.Val, _ = strconv.Atoi(a)
	fmt.Printf("Start create deep: %d node: %d.\r\n", d, tree.Val)
	if lr != "root" {
		fmt.Printf("**Current parent node: %d\r\n", parent)
	}
	tree.Left = createTree("left", d+1, tree.Val)
	fmt.Printf("Back to deep: %d node: %d.\r\n", d, tree.Val)
	tree.Right = createTree("right", d+1, tree.Val)
	fmt.Printf("Back to deep: %d node: %d.\r\n", d, tree.Val)

	fmt.Printf("Create deep: %d node: %d successed.\r\n", d, tree.Val)
	return tree
}

Full Code