interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / drafts / rosettacode / tree-traversal.wiki

128 lines · 2120 bytes Raw Blame History
1=={{header|Omegese}}==
2{{works with|omc|sha256 2c824805, aien-dev/omega-mv e5b32567, Linux AArch64}}
3Omega has no imports, so the small output helpers (<code>emit</code> and friends) are part of the program.
4<syntaxhighlight lang="text">
5om2
6text nl "\n"
7text sp " "
8text minus "-"
9text tpre "preorder: "
10text tin "inorder: "
11text tpost "postorder: "
12text tlevel "level-order:"
13global lft ulong 10
14global rgt ulong 10
15global queue ulong 10
16note emit writes every byte of a to stdout; a short write is retried, an error exits 1
17fn emit a view uchar * to void
18o = ulong 0
19while lt o len a bound 4096
20k = write 1 a o sub len a o
21if le k 0
22exit 1
23end
24o = add o ulong k
25end
26end
27note emitu writes n in decimal; 20 digits hold every ulong
28fn emitu n ulong to void
29d = new uchar 20 0
30i = ulong 20
31v = n
32while true bound 20
33i = sub i 1
34put d i uchar add rem v 10 48
35v = div v 10
36if eq v 0
37break
38end
39end
40emit part d i sub 20 i
41end
42note the task's tree, nodes 1..9 with 0 for no child:
43note 1
44note / \
45note 2 3
46note / \ /
47note 4 5 6
48note / / \
49note 7 8 9
50fn kids n ulong l ulong r ulong to void
51put lft n l
52put rgt n r
53end
54fn pre n ulong to void
55if eq n 0
56ret
57end
58emit sp
59emitu n
60pre get lft n
61pre get rgt n
62end
63fn ino n ulong to void
64if eq n 0
65ret
66end
67ino get lft n
68emit sp
69emitu n
70ino get rgt n
71end
72fn post n ulong to void
73if eq n 0
74ret
75end
76post get lft n
77post get rgt n
78emit sp
79emitu n
80end
81note level order reads nodes from a queue; each node enters it once, so 9 passes suffice
82fn level n ulong to void
83put queue 0 n
84h = ulong 0
85t = ulong 1
86while lt h t bound 9
87v = get queue h
88h = add h 1
89emit sp
90emitu v
91if ne get lft v 0
92put queue t get lft v
93t = add t 1
94end
95if ne get rgt v 0
96put queue t get rgt v
97t = add t 1
98end
99end
100end
101fn main to int
102kids 1 2 3
103kids 2 4 5
104kids 3 6 0
105kids 4 7 0
106kids 6 8 9
107emit tpre
108pre 1
109emit nl
110emit tin
111ino 1
112emit nl
113emit tpost
114post 1
115emit nl
116emit tlevel
117level 1
118emit nl
119ret 0
120end
121</syntaxhighlight>
122{{out}}
123<pre>
124preorder: 1 2 4 7 5 3 6 8 9
125inorder: 7 4 2 5 1 8 6 9 3
126postorder: 7 4 5 2 8 9 6 3 1
127level-order: 1 2 3 4 5 6 7 8 9
128</pre>