You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MIPS中实现二叉树直径?已完成树高计算

我之前已经在这个问题上取得了一些进展,现在正尝试在MIPS汇编中实现二叉树直径的计算。特别感谢Peter Cordes在我之前的相关提问中提供的帮助——我已经完成了二叉树高度的MIPS实现,代码运行完全正常,但在计算二叉树直径时遇到了瓶颈。

已实现的二叉树高度MIPS代码

.data 
tree: .word a 
a: .word 5, bb, c 
bb: .word 2, d, e 
c: .word 1, 0, 0 
d: .word 5, f, g 
e: .word 9, 0, h 
f: .word 0, 0, 0 
g: .word 6, i, 0 
h: .word 55, 0, jj 
i: .word 4, 0, 0 
jj: .word 8, 0, 0 

.text 
main: 
    la $a0, tree 
    lw $a0,0($a0) 
    jal heightOfTree 
    move $a0, $v0 
    li $v0, 1       # Print the return value 
    syscall 
    li $v0, 10 
    syscall 

heightOfTree: 
    bnez $a0, Recursion 
    li $v0, 0       # Base case 
    jr $ra 

Recursion: 
    # Recursive call: height of tree = max(height(leftchild), height(rightchild)) + 1
    addiu $sp, $sp, -12 
    sw $ra, 0($sp) 
    sw $a0, 4($sp) 

    lw $a0, 4($a0)  # height(rightchild)
    jal heightOfTree 
    sw $v0, 8($sp)  # Saving the height of the left child 

    lw $a0, 4($sp)  # Taking the Address of the root 
    lw $a0, 8($a0)  # height of right child 
    jal heightOfTree 

    lw $t0, 8($sp)  # In $t0 the height of the left child, In $v0 of the right child.
    bge $v0, $t0, maximum 
    move $v0, $t0 

maximum: 
    addiu $v0, $v0, 1 
    lw $ra, 0($sp) 
    addiu $sp, $sp, 12 
    jr $ra          # Returning the height to the main 

参考的C语言直径实现逻辑

我参考的C语言实现逻辑如下,核心思路是计算每个节点的左右子树高度之和,再和左右子树的直径取最大值:

int diameter (node *P) { 
    if (p==NULL) return 0; 
    int lheight = height(P->left); 
    int rheight = height(P->right); 
    int ldiameter = diameter(p->left); 
    int rdiameter = diameter(p->right); 
    int longestpath = max (lheight+rheight+1, max(ldiameter, rdiameter));
    return longestpath; 
}

按照这个C逻辑编写MIPS代码时,我始终无法得到正确结果——测试用的这个二叉树,预期直径应该是7,但我的实现一直没能算出这个值。

内容的提问来源于stack exchange,提问作者Kukuriku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:06:07