This code seems a bit bulky than needed. Any tips on how to write it differently ? It simply updates the height of a node in a binary tree, based on its children.
func (tree *Tree) insert(val int) *Tree {
if tree == nil {
return &Tree{nil, val, 0, nil}
}
tree.Height++ // increase at every insert the height of the node.
if tree.Value > val {
tree.Left = tree.Left.insert(val)
return tree
}
tree.Right = tree.Right.insert(val)
return tree
}
func (n *Node) updateHeight() {
if n == nil {
return
}
h := -1
if n.Left != nil {
h = n.Left.Height
}
if n.Right != nil && h.Right.Height > h {
h = n.Right.Height
}
n.Height = h + 1
}
Best version so far, I like it a lot. Just wondering though, instead of calling the auxiliary variable h, I would call it maxChildHeight.
In reality I rarely call an auxiliary variable it with a large name, just to explain what it does, but in this case I feel it would help make understanding the method more easily.
func (n *Node) Height() int {
if n == nil {
return -1
}
return max(n.Left.Height(), n.Right.Height()) + 1
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Now you do not need to updateHeight(), just use Height().