Skip to content

Commit b83171a

Browse files
committed
add depth method to bst
1 parent 5724286 commit b83171a

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

data-structures/binary-tree/binary-search-tree.go

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,17 @@ type node struct {
1313
right *node
1414
}
1515

16-
type tree struct {
16+
type btree struct {
1717
root *node
1818
}
1919

20+
func max(a, b int) int {
21+
if a > b {
22+
return a
23+
}
24+
return b
25+
}
26+
2027
func newNode(val int) *node {
2128
return &node{val, nil, nil}
2229
}
@@ -75,14 +82,27 @@ func bst_delete(root *node, val int) *node {
7582
return root
7683
}
7784

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+
7897
/*
7998
func main() {
80-
t := &tree{nil}
99+
t := &btree{nil}
81100
inorder(t.root)
82101
t.root = insert(t.root, 10)
83102
t.root = insert(t.root, 20)
84103
t.root = insert(t.root, 15)
85104
t.root = insert(t.root, 30)
105+
fmt.Print(t.depth(), "\n")
86106
inorder(t.root)
87107
fmt.Print("\n")
88108
t.root = bst_delete(t.root, 10)
@@ -97,5 +117,6 @@ func main() {
97117
t.root = bst_delete(t.root, 20)
98118
inorder(t.root)
99119
fmt.Print("\n")
120+
fmt.Print(t.depth(), "\n")
100121
}
101122
*/

0 commit comments

Comments
 (0)