I'm trying to write a function that calculates the height of a tree using this algorithm:
height(root)
if root == nil then return 0
h1 = height(root.left)
h2 = height(root.right)
answer = max(h1,h2) +1
return answer
first I call the function passing the root, the the base case, if the tree is null the height is zero, else call the recursion on the left son of the root and store the value, then call the recursion on the right son of the root and store the value, then the height is simply the maximum value between the left and right son plus the root.
I've implemented this in mars but I received: Error in /Users/mips1.asm line 47: Runtime exception at 0x0040004c: store address not aligned on word boundary 0x00000007
.data
tree: .word a
a: .word 3, y, c
y: .word 21, d, e
c: .word 4, 0, 0
d: .word 5, f, g
e: .word -3, 0, h
f: .word 6, 0, 0
g: .word 9, i, 0
h: .word 18, 0, w
i: .word 22, 0, 0
w: .word 1, 0, 0
answer: .word 0
.text
.globl main
main:
la $v0, a
lw $a0, 0($v0)
jal height
sw $v0, answer
#print
li $v0,1
lw $a0, answer
syscall
#end
li $v0, 10
syscall
#________________________________________
#height
.globl height
height:
addi $sp, $sp, -12
sw $ra, 0($sp)
sw $s0, 4($sp)
#base case
li $v0, 0
beq $a0, 0, leaf
move $s0, $a0
sw $a0, 4($a0) #x.left
jal height
sw $a0, 8($a0) #x.right
jal height
#answer = max(heigtLeft, heigtRight)+1
leaf:
lw $ra, 0($sp)
lw $s0, 4($sp)
addi $sp, $sp, 8
jr $ra
User contributions licensed under CC BY-SA 3.0