Fortran 77-1085个字符
subroutine q(u,t)
implicit integer(i-z)
character*33 f,g
dimension t(u)
m=ceiling(log(real(u))/log(2.))
v=2**(m+1)-1
do l=1,m
n=2**(l-1)
k=2**(m-l+2)-3
w=(3+k)*2**(l-1)-k
p=1+(v-w)/2
if(l.ne.1)then
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
do j=2**(l-1),2**l-1
if(t(j/2).lt.0.or.t(j).lt.0)then
print f,' ',' '
elseif(mod(j,2).eq.0)then
print f,' /',' '
else
print f,' \ ',' '
endif
enddo
print*
endif
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
write(g,'(A2,I3,A3)')'(A',k+3,',$)'
do j=2**(l-1),2**l-1
if(t(j).ge.0)then
print f,t(j),' '
else
print g,' '
endif
enddo
print*
enddo
end
树t
以通常的方式在输入数组中表示,根在1处,root->左在2处,根->右在3处根->左->左在4处...
输出应适合多达5级深度的常规端子。
我在每对节点之间使用一个斜杠,一旦有四个或更多的级别,在顶部附近看起来就很傻了。我最多允许三个数字节点。
带有注释和启动支架的完整程序:
program tree
parameter (l=8) ! How many nodes to support
dimension i(l)
c Initialize the array to all empty nodes
do j=1,l
i(j)=-1
end do
c Fill in some values
i(1)=3
i(2)=1
i(3)=5
i(5)=2
i(6)=4
i(7)=7
c i(14)=6
c i(15)=8
c Call the printing routine
call q(l,i)
stop
end
c Print an ASCII representation of the tree
c
c u the length of the array containing the tree
c t an integer array representing the tree.
c
c The array contains only non-negative values, and empty nodes are
c represented in the array with -1.
c
c The printed representation uses three characters for every node,
c and places the (back) slash equally between the two node-centers.
subroutine q(u,t)
implicit integer(i-z)
character*33 f,g
dimension t(u)
m=ceiling(log(real(u))/log(2.)) ! maximum depth of the tree
v=2**(m+1)-1 ! width needed for printing the whole tree
! Optimized from 3*2**m + 1*((2**m)-1) at
! the bottom level
do l=1,m
n=2**(l-1) ! number of nodes on this level
k=2**(m-l+2)-3 ! internode spacing
w=(3+k)*2**(l-1)-k ! width needed for printing this row
! Optimized from 3*2**l + k*((2**l)-1) at
! the bottom level
p=1+(v-w)/2 ! padding for this row
c Print the connecting lines associated with the previous level
if(l.ne.1)then ! Write the connecting lines
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(A3,A',k,',$)'
do j=2**(l-1),2**l-1
if(t(j/2).lt.0.or.t(j).lt.0)then
print f,' ',' '
elseif(mod(j,2).eq.0)then
print f,' /',' '
else
print f,' \ ',' '
endif
enddo
print*
endif
c Print the nodes on this level
write(f,'(A,I3,A)')'(A',p,',$)'
print f,' '
write(f,'(A5,I3,A3)')'(I3,A',k,',$)'
write(g,'(A2,I3,A3)')'(A',k+3,',$)'
do j=2**(l-1),2**l-1
if(t(j).ge.0)then
print f,t(j),' '
else
print g,' '
endif
enddo
print*
enddo
end
输入等于示例的输出:
$ ./a.out
3
/ \
1 5
\ / \
2 4 7