This sample code uses dynamic objects to create a binary tree of random numbers. It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing through the tree.
For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
call function 'RANDOM_I4'
exporting
rnd_min = 0
rnd_max = 100
importing
rnd_value = int.
* store numbers
rnd-num = int.
append rnd.
* build binary tree of random numbers
perform add_value using tree int.
enddo.
* stored numbers are sorted for comparison
sort rnd by num.
* print sorted random numbers
write: / 'Sorted Numbers'.
write: / '=============='.
skip.
loop at rnd.
write: rnd-num.
endloop.
skip.
* print binary tree. This should give the same result
* as the one listed from the internal table
write: / 'Binary Tree List'.
write: / '================'.
skip.
perform print_value using tree.
skip.
*&---------------------------------------------------------------------*
*& Form add_value
*&---------------------------------------------------------------------*
* text - Build tree with value provided
*----------------------------------------------------------------------*
* -->TREE text
* -->VAL text
*----------------------------------------------------------------------*
form add_value using tree type stree val type i.
field-symbols: <ltree> type any.
data: work type stree.
if tree is initial. "When node has no values
tree-value = val. " assign value
clear: tree-left, tree-right.
create data tree-left type stree. "Create an empty node for left
create data tree-right type stree. "create an empty node for right
else.
if val le tree-value. "if number is less than or equal
assign tree-left->* to <ltree>. "assign the left node to fs
* call add_value recursively with left node
perform add_value using <ltree> val.
else. "if number is greater
assign tree-right->* to <ltree>. "assign the right node to fs
* call add_value recursively with right node
perform add_value using <ltree> val.
endif.
endif.
endform. "add_value
*&---------------------------------------------------------------------*
*& Form print_value
*&---------------------------------------------------------------------*
* text - traverse tree from left-mid-right order
* automatically this will be sorted list
*----------------------------------------------------------------------*
* -->TREE text
*----------------------------------------------------------------------*
form print_value using tree type stree.
field-symbols: <ltree> type any.
if tree is initial. "node is empty
else. "non-empty node
assign tree-left->* to <ltree>. "left node
perform print_value using <ltree>. "print left
write: tree-value. "print the current value
assign tree-right->* to <ltree>. "right node
perform print_value using <ltree>. "print right
endif.
endform. "print_value