@@ -13,10 +13,17 @@ type node struct {
13
13
right * node
14
14
}
15
15
16
- type tree struct {
16
+ type btree struct {
17
17
root * node
18
18
}
19
19
20
+ func max (a , b int ) int {
21
+ if a > b {
22
+ return a
23
+ }
24
+ return b
25
+ }
26
+
20
27
func newNode (val int ) * node {
21
28
return & node {val , nil , nil }
22
29
}
@@ -75,14 +82,27 @@ func bst_delete(root *node, val int) *node {
75
82
return root
76
83
}
77
84
85
+ // helper function for t.depth
86
+ func _calculate_depth (n * node , depth int ) int {
87
+ if n == nil {
88
+ return depth
89
+ }
90
+ return max (_calculate_depth (n .left , depth + 1 ), _calculate_depth (n .right , depth + 1 ))
91
+ }
92
+
93
+ func (t * btree ) depth () int {
94
+ return _calculate_depth (t .root , 0 )
95
+ }
96
+
78
97
/*
79
98
func main() {
80
- t := &tree {nil}
99
+ t := &btree {nil}
81
100
inorder(t.root)
82
101
t.root = insert(t.root, 10)
83
102
t.root = insert(t.root, 20)
84
103
t.root = insert(t.root, 15)
85
104
t.root = insert(t.root, 30)
105
+ fmt.Print(t.depth(), "\n")
86
106
inorder(t.root)
87
107
fmt.Print("\n")
88
108
t.root = bst_delete(t.root, 10)
@@ -97,5 +117,6 @@ func main() {
97
117
t.root = bst_delete(t.root, 20)
98
118
inorder(t.root)
99
119
fmt.Print("\n")
120
+ fmt.Print(t.depth(), "\n")
100
121
}
101
122
*/
0 commit comments