BTS中最长的路径,如何做直径

时间:2018-05-16 16:50:25

标签: assembly mips

我已经提出了一个问题,但我确实取得了进展。 所以我试图在MIPS中实现树的直径。

感谢Peter Cordes帮助我找出了一些事情on my previous question about this。 所以我已经实现了树的高度:

.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 # Calcolating the max between the left and right (left height - $t0)(right -height - $v0)
move $v0, $t0
maximum: 
addiu $v0, $v0, 1
lw $ra, 0($sp)
addiu $sp, $sp, 12
jr $ra #Returning the height to the main

它很完美,但我没有成功计算直径:(

我正在使用此代码

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

直径应为7

0 个答案:

没有答案