Skip to content

Commit 216e24a

Browse files
committed
add binary tree
1 parent c7447ef commit 216e24a

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// basic binary tree and related operations
2+
3+
package binarytree
4+
5+
// package main
6+
7+
import "fmt"
8+
9+
type node struct {
10+
val int
11+
left *node
12+
right *node
13+
}
14+
15+
type btree struct {
16+
root *node
17+
}
18+
19+
func max(a, b int) int {
20+
if a > b {
21+
return a
22+
}
23+
return b
24+
}
25+
26+
func newNode(val int) *node {
27+
n := &node{val, nil, nil}
28+
return n
29+
}
30+
31+
func inorder(n *node) {
32+
if n == nil {
33+
return
34+
}
35+
inorder(n.left)
36+
fmt.Print(n.val, " ")
37+
inorder(n.right)
38+
}
39+
40+
func preorder(n *node) {
41+
if n == nil {
42+
return
43+
}
44+
fmt.Print(n.val, " ")
45+
inorder(n.left)
46+
inorder(n.right)
47+
}
48+
49+
func postorder(n *node) {
50+
if n == nil {
51+
return
52+
}
53+
inorder(n.left)
54+
inorder(n.right)
55+
fmt.Print(n.val, " ")
56+
}
57+
58+
func levelorder(root *node) {
59+
var q []*node // queue
60+
var n *node // temporary node
61+
62+
q = append(q, root)
63+
64+
for len(q) != 0 {
65+
n, q = q[0], q[1:]
66+
fmt.Print(n.val, " ")
67+
if n.left != nil {
68+
q = append(q, n.left)
69+
}
70+
if n.right != nil {
71+
q = append(q, n.right)
72+
}
73+
}
74+
}
75+
76+
// helper function for t.depth
77+
func _calculate_depth(n *node, depth int) int {
78+
if n == nil {
79+
return depth
80+
}
81+
return max(_calculate_depth(n.left, depth+1), _calculate_depth(n.right, depth+1))
82+
}
83+
84+
func (t *btree) depth() int {
85+
return _calculate_depth(t.root, 0)
86+
}
87+
88+
/*
89+
func main() {
90+
t := btree{nil}
91+
t.root = newNode(0)
92+
t.root.left = newNode(1)
93+
t.root.right = newNode(2)
94+
t.root.left.left = newNode(3)
95+
t.root.left.right = newNode(4)
96+
t.root.right.left = newNode(5)
97+
t.root.right.right = newNode(6)
98+
t.root.right.right.right = newNode(10)
99+
100+
inorder(t.root)
101+
fmt.Print("\n")
102+
preorder(t.root)
103+
fmt.Print("\n")
104+
postorder(t.root)
105+
fmt.Print("\n")
106+
levelorder(t.root)
107+
fmt.Print("\n")
108+
fmt.Print(t.depth(), "\n")
109+
}
110+
*/

0 commit comments

Comments
 (0)