#------start code---------------------------------
# in: $a0, the parent node that
#---------------------------------------
printtree:
subu $sp,$sp,8
sw $ra,4($sp) #save ra
sw $a0,8($sp) #push node
lw $a0,12($sp) #access argument node to $a0
j ptexit
ptloop:
subu $sp,$sp,4
lw $a0,4($a0)
sw $a0,4($sp) #push [esi+4]
jal printtree #call printtree2
add $sp,$sp,8
lw $a1,0($a0) #at this point $a0 holds a node
lw $a1,0($a1)
jal printInteger #this function just prints value of $a1
lw $a0,12($a0)
ptexit:
bnez $a0,ptloop #jump ptloop if $a0 ne to zero
lw $ra,4($sp)
lw $a0,8($sp) #get the returned values from the stack back to $a0
add $sp,$sp,8
jr $r #go to $ra
#----------end code--------
上面的代码应该打印从最小到最高的二叉树 给定顶部节点,在某处,某种程度上会破坏堆栈,导致异常。非常感谢
答案 0 :(得分:0)
最近修复了它,并且据我测试它工作正常。使用它,将父节点传递给0($ sp),如下面的代码:
sub $sp,$sp,4
sw $v1,0($sp)
jal printtree
add $sp,$sp,4
printtree:
sub $sp,$sp,8
sw $a0,0($sp) #save orig $a0 as new TOS
sw $ra,4($sp) #save return address as TOS+4
lw $a0,8($sp) #access param1 in TOS+8
j leftmost
recur:
sub $sp,$sp,4
lw $a1,4($a0) #access node->left
sw $a1,0($sp) #push it to the stack
jal printtree
lw $a1,0($a0) # $a1 should contain node->data
jal printInteger # calls a syscall function that prints $a1 value to console
#node is assumed to be in $a0
lw $a0,8($a0) #access node->right
leftmost:
bne $a0,$zero,recur
lw $a0,0($sp) #hold the previous node
lw $ra,4($sp) #hold the return address
add $sp,$sp,12
jr $ra