Tree traversal: Difference between revisions

m
No edit summary
 
(35 intermediate revisions by 15 users not shown)
Line 34:
{{trans|Python: Class based}}
 
<langsyntaxhighlight lang="11l">T Node
Int data
Node? left
Line 44:
.right = right
 
F preorder(visitor) -> NVoid
visitor(.data)
I .left != N
Line 51:
.right.preorder(visitor)
 
F inorder(visitor) -> NVoid
I .left != N
.left.inorder(visitor)
Line 58:
.right.inorder(visitor)
 
F postorder(visitor) -> NVoid
I .left != N
.left.postorder(visitor)
Line 65:
visitor(.data)
 
F preorder2(&d, level = 0) -> NVoid
d[level].append(.data)
I .left != N
Line 105:
print(‘levelorder: ’, end' ‘’)
tree.levelorder(printwithspace)
print()</langsyntaxhighlight>
 
{{out}}
Line 114:
levelorder: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|8080 Assembly}}==
<syntaxhighlight lang="asm8080"> org 100h
jmp demo
;;; Traverse tree at DE according to method at BC.
;;; Call routine at HL with DE=<value> for each value encounterd.
travrs: shld trvcb+1 ; Store routine pointer
xchg ; Tree in HL
push b ; Jump to method BC
ret
;;; Preorder traversal
preo: mov a,h
ora l
rz ; Null node = stop
mov e,m
inx h
mov d,m ; Load value
inx h
push h ; Handle value
call trvcb
pop h ; Left node
mov e,m
inx h
mov d,m
inx h
push h ; Save pointer
xchg
call preo
pop h
mov e,m
inx h ; Right node
mov d,m
xchg
jmp preo
;;; Inorder traversal
ino: mov a,h
ora l
rz ; Null node = stop
mov e,m
inx h
mov d,m ; Load value
inx h
push d ; Save value on stack
mov e,m
inx h
mov d,m
inx h ; Load left node
push h ; Save pointer on stack
xchg
call ino ; Traverse left node
pop h
pop d ; Get value
push h
call trvcb ; Handle value
pop h
mov e,m
inx h
mov d,m
xchg
jmp ino ; Traverse right node
;;; Postorder traversal
posto: mov a,h
ora l
rz ; Null node = stop
mov e,m
inx h
mov d,m ; Load value
inx h
push d ; Keep value on stack
mov e,m
inx h
mov d,m
inx h ; Load left node
push h
xchg
call posto ; Traverse left node
pop h
mov e,m
inx h
mov d,m ; Load right node
xchg
call posto ; Traverse right node
pop d ; Get value from stack
jmp trvcb ; Handle value
;;; Level-order traversal
lvlo: shld queue ; Store current node at beginning of queue
lxi h,queue ; HL = Queue start pointer
lxi b,queue+2 ; BC = Queue end pointer
lvllp: mov a,h ; When start == end, stop
cmp b
jnz lvlt ; Not equal
mov a,l
cmp c
rz ; Equal = stop
lvlt: mov e,m ; Load current node in DE
inx h
mov d,m
inx h
mov a,d ; Null node = ignore
ora e
jz lvllp
push h ; Keep queue start pointer
xchg ; HL = current node
mov e,m ; Load value into DE
inx h
mov d,m
inx h
push h ; Keep pointer to left and right nodes
push b ; And pointer to end of queue
call trvcb ; Handle value
pop b ; Restore pointer to end of queue
pop h ; Restore pointer to left and right nodes
mvi d,4 ; D = copy counter
lvlcp: mov a,m ; Copy left and right nodes to queue
stax b
inx h
inx b
dcr d
jnz lvlcp
pop h ; Restore queue stack pointer
jmp lvllp
trvcb: jmp 0 ; Callback pointer
 
;;; Run examples
demo: lhld 6 ; Move stack to top of memory
sphl
lxi h,0 ; So we can still RET out of the program
push h
lxi h,orders
order: mov e,m ; Get string
inx h
mov d,m
inx h
mov a,e ; 0 = done
ora d
rz
push h ; Print string
call print
pop h
mov c,m ; Load method in BC
inx h
mov b,m
inx h
push h
lxi d,tree ; Tree in DE
lxi h,cb ; Callback in HL
call travrs ; Traverse the tree
lxi d,nl
call print ; Newline
pop h ; Restore table pointer
jmp order
 
;;; Print the tree value. They're all <10 for the example, so we
;;; don't need multiple digits.
cb: mvi a,'0'
add e
sta nstr
lxi d,nstr
print: mvi c,9 ; CP/M print string call
jmp 5
nstr: db '* $'
nl: db 13,10,'$'
 
;;; Example tree
tree: dw 1, node2, node3
node2: dw 2, node4, node5
node3: dw 3, node6, 0
node4: dw 4, node7, 0
node5: dw 5, 0, 0
node6: dw 6, node8, node9
node7: dw 7, 0, 0
node8: dw 8, 0, 0
node9: dw 9, 0 ,0
 
;;; Table of names and orders
orders: dw spreo,preo
dw sino,ino
dw sposto,posto
dw slvlo,lvlo
dw 0
spreo: db 'Preorder: $'
sino: db 'Inorder: $'
sposto: db 'Postorder: $'
slvlo: db 'Level-order: $'
 
queue: equ $ ; Put level-order queue on heap</syntaxhighlight>
{{out}}
<pre>Preorder: 1 2 4 7 5 3 6 8 9
Inorder: 7 4 2 5 1 8 6 9 3
Postorder: 7 4 5 2 8 9 6 3 1
Level-order: 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|8086 Assembly}}==
<syntaxhighlight lang="nasm"> cpu 8086
org 100h
section .text
jmp demo
;;; Traverse tree at SI. Call routine at CX with values in AX.
;;; CX must preserve BX, CX, SI, DI.
;;; Preorder traversal
preo: test si,si
jz pdone ; Zero pointer = done
lodsw ; Load value
call cx ; Handle value
push si ; Keep value
mov si,[si] ; Load left node
call preo ; Traverse left node
pop si
mov si,[si+2] ; Load right node
jmp preo ; Traverse right node
;;; Inorder traversal
ino: test si,si
jz pdone ; Zero pointer = done
push si
mov si,[si+2] ; Load left node
call ino ; Traverse left node
pop si
lodsw ; Load value
call cx ; Handle value
mov si,[si+2] ; Load right node
jmp ino ; Traverse right node
;;; Postorder traversal
posto: test si,si
jz pdone ; Zero pointer = done
push si
mov si,[si+2] ; Load left node
call posto ; Traverse left node
pop si
push si
mov si,[si+4] ; Load right node
call posto
pop si ; Load value
lodsw
jmp cx ; Handle value
pdone: ret
;;; Level-order traversal
lvlo: mov di,queue ; DI = queue end pointer
mov ax,si
mov si,di ; SI = queue start pointer
stosw
.step: cmp di,si ; If end == start, done
je pdone
lodsw ; Get next item
test ax,ax ; Null?
jz .step
mov bx,si ; Keep start pointer in BX
mov si,ax ; Load item
lodsw ; Get value
call cx ; Handle value
lodsw ; Copy nodes to queue
stosw
lodsw
stosw
mov si,bx ; Put start pointer back
jmp .step
 
;;; Demo code
demo: mov si,orders
.loop: lodsw ; Load next order
test ax,ax
jz .done
mov dx,ax ; Print order name
mov ah,9
int 21h
lodsw ; Load order routine
mov bp,si ; Keep SI
mov si,tree ; Traverse the tree
mov cx,pdgt ; Printing the digits
call ax
mov si,bp
jmp .loop
.done: ret
 
;;; Callback: print single digit
pdgt: add al,'0'
mov [.str],al
mov ah,9
mov dx,.str
int 21h
ret
.str: db '* $'
 
section .data
;;; List of orders
orders: dw .preo,preo
dw .ino,ino
dw .posto,posto
dw .lvlo,lvlo
dw 0
.preo: db 'Preorder: $'
.ino: db 13,10,'Inorder: $'
.posto: db 13,10,'Postorder: $'
.lvlo: db 13,10,'Level-order: $'
 
;;; Exampe tree
tree: dw 1,.n2,.n3
.n2: dw 2,.n4,.n5
.n3: dw 3,.n6,0
.n4: dw 4,.n7,0
.n5: dw 5,0,0
.n6: dw 6,.n8,.n9
.n7: dw 7,0,0
.n8: dw 8,0,0
.n9: dw 9,0,0
 
section .bss
queue: resw 256</syntaxhighlight>
{{out}}
<pre>Preorder: 1 2 4 7 5 3 6 8 9
Inorder: 7 4 2 5 1 8 6 9 3
Postorder: 7 4 5 2 8 9 6 3 1
Level-order: 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deftree64.s */
Line 505 ⟶ 817:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight lang="lisp">(defun flatten-preorder (tree)
(if (endp tree)
nil
Line 554 ⟶ 866:
(defun flatten-level (tree)
(let ((levels (flatten-level-r1 tree 0 nil)))
(flatten-level-r2 levels (len levels))))</langsyntaxhighlight>
 
=={{header|Action!}}==
Line 560 ⟶ 872:
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 810 ⟶ 1,122:
 
DestroyTree(t)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Tree_traversal.png Screenshot from Atari 8-bit computer]
Line 821 ⟶ 1,133:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
Line 928 ⟶ 1,240:
New_Line;
Destroy_Tree(N);
end Tree_traversal;</langsyntaxhighlight>
 
=={{header|Agda}}==
<langsyntaxhighlight Agdalang="agda">open import Data.List using (List; _∷__?_; []; concat)
open import Data.Nat using (N; suc; zero)
open import Level using (Level)
open import Relation.Binary.PropositionalEquality using (_≡__=_; refl)
 
data Tree {a} (A : Set a) : Set a where
leaf : Tree A
node : A ? Tree A ? Tree A ? Tree A
 
variable
Line 944 ⟶ 1,256:
A : Set a
 
preorder : Tree A ? List A
preorder tr = go tr []
where
go : Tree A ? List A ? List A
go leaf ys = ys
go (node x ls rs) ys = x ? go ls (go rs ys)
 
inorder : Tree A ? List A
inorder tr = go tr []
where
go : Tree A ? List A ? List A
go leaf ys = ys
go (node x ls rs) ys = go ls (x ? go rs ys)
 
postorder : Tree A ? List A
postorder tr = go tr []
where
go : Tree A ? List A ? List A
go leaf ys = ys
go (node x ls rs) ys = go ls (go rs (x ? ys))
 
level-order : Tree A ? List A
level-order tr = concat (go tr [])
where
go : Tree A ? List (List A) ? List (List A)
go leaf qs = qs
go (node x ls rs) [] = (x ? []) ? go ls (go rs [])
go (node x ls rs) (q ? qs) = (x ? q ) ? go ls (go rs qs)
 
example-tree : Tree N
example-tree =
node 1
Line 995 ⟶ 1,307:
leaf)
 
_ : preorder example-tree = 1 ? 2 ? 4 ? 7 ? 5 ? 3 ? 6 ? 8 ? 9 ? []
_ = refl
 
_ : inorder example-tree = 7 ? 4 ? 2 ? 5 ? 1 ? 8 ? 6 ? 9 ? 3 ? []
_ = refl
 
_ : postorder example-tree = 7 ? 4 ? 5 ? 2 ? 8 ? 9 ? 6 ? 3 ? 1 ? []
_ = refl
 
_ : level-order example-tree = 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? []
_ = refl</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 1,017 ⟶ 1,329:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<langsyntaxhighlight lang="algol68">MODE VALUE = INT;
PROC value repr = (VALUE value)STRING: whole(value, 0);
 
Line 1,140 ⟶ 1,452:
 
destroy tree(node)
)</langsyntaxhighlight>
Output:
<pre>
Line 1,152 ⟶ 1,464:
 
Written in Dyalog APL with dfns.
<langsyntaxhighlight APLlang="apl">preorder ? {l r←⍺r?? ⍵⍵?? ? ? (⊃r?r)∇⍨⍣???(×≢r×?r)?(⊃l?l)∇⍨⍣???(×≢l×?l)⊢⍺?? ⍺⍺?? ?}
inorder ? {l r←⍺r?? ⍵⍵?? ? ? (⊃r?r)∇⍨⍣???(×≢r×?r)⊢⍵?? ⍺⍺⍨???(⊃l?l)∇⍨⍣???(×≢l×?l)⊢⍺??}
postorder? {l r?? ?? ? ? ? ???(?r)???(×?r)?(?l)???(×?l)??}
postorder← {l r←⍺ ⍵⍵ ⍵ ⋄ ⍵ ⍺⍺⍨(⊃r)∇⍨⍣(×≢r)⊢(⊃l)∇⍨⍣(×≢l)⊢⍺}
lvlorder ? {0=⍴⍵??:? ? (⊃⍺⍺⍨????/(⌽⍵??),⊂⍺??)∇⊃∘??°(,/)⍣2⊢⍺∘⍵⍵?2??°??¨?}</langsyntaxhighlight>
These accept four arguments (they are operators, a.k.a. higher-order functions):
<pre>acc visit ___order children bintree</pre>
Line 1,174 ⟶ 1,486:
and empty childL or childR mean and absence of the corresponding child node.
 
<langsyntaxhighlight APLlang="apl">tree←1tree?1(2(4(7⍬⍬7??)?)(5⍬⍬5??))(3(6(8⍬⍬8??)(9⍬⍬9??))?)
visit?{?,(×??)???}
visit←{⍺,(×≢⍵)⍴⊃⍵}
children←children?{?¨@(×∘≢×°?¨)1↓⍵1??}</langsyntaxhighlight>
Each time the accumulator is initialised as an empty list. Visiting a node means to append its data to the accumulator, and generating children is fetching the two corresponding sublists in the nested array if they're non-empty.<br>
My input into the interactive APL session is indented by 6 spaces.
<pre>
? visit preorder children tree
1 2 4 7 5 3 6 8 9
? visit inorder children tree
7 4 2 5 1 8 6 9 3
? visit postorder children tree
7 4 5 2 8 9 6 3 1
? visit lvlorder children ,⊂tree?tree
1 2 3 4 5 6 7 8 9
</pre>
Line 1,198 ⟶ 1,510:
=={{header|AppleScript}}==
{{Trans|JavaScript}}(ES6)
<langsyntaxhighlight AppleScriptlang="applescript">on run
-- Sample tree of integers
set tree to node(1, ¬
Line 1,212 ⟶ 1,524:
-- 'Visualize a Tree':
set strTree to unlines({¬
" + 4 - 7", ¬
" + 2 ¦", ¬
" ¦ + 5", ¬
" 1 ¦", ¬
" ¦ + 8", ¬
" + 3 - 6 ¦", ¬
" + 9"})
script tabulate
on |λ?|(s, xs)
justifyRight(14, space, s & ": ") & unwords(xs)
end |λ?|
end script
Line 1,249 ⟶ 1,561:
-- inorder :: a -> [[a]] -> [a]
on inorder(x, xs)
if {} ? xs then
item 1 of xs & x & concat(rest of xs)
else
Line 1,272 ⟶ 1,584:
on foldTree(f)
script
on |λ?|(tree)
script go
property g : |λ?| of mReturn(f)
on |λ?|(oNode)
g(root of oNode, |λ?|(nest of oNode) ¬
of map(go))
end |λ?|
end script
|λ?|(tree) of go
end |λ?|
end script
end foldTree
Line 1,306 ⟶ 1,618:
tell mReturn(contents of f)
repeat with x in xs
set end of lst to |λ?|(contents of x)
end repeat
end tell
Line 1,336 ⟶ 1,648:
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ?|(item i of xs, v, i, xs)
end repeat
return v
Line 1,369 ⟶ 1,681:
-- values of each level of the tree.
script go
on |λ?|(node, a)
if {} ? a then
tell a to set {h, t} to {item 1, rest}
else
Line 1,377 ⟶ 1,689:
{{root of node} & h} & foldr(go, t, nest of node)
end |λ?|
end script
|λ?|(tree, {}) of go
end levels
 
Line 1,390 ⟶ 1,702:
else
script
property |λ?| : f
end script
end if
Line 1,401 ⟶ 1,713:
-- to each element of xs.
script
on |λ?|(xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ?|(item i of xs, i, xs)
end repeat
return lst
end tell
end |λ?|
end script
end map
Line 1,473 ⟶ 1,785:
set ys to {}
repeat with i from 1 to n
set v to |λ?|() of xs
if missing value is v then
return ys
Line 1,518 ⟶ 1,830:
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ?|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre> + 4 - 7
+ 2 ¦
¦ + 5
1 ¦
¦ + 8
+ 3 - 6 ¦
+ 9
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
Line 1,538 ⟶ 1,850:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,975 ⟶ 2,287:
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,022 ⟶ 2,334:
 
=={{header|ATS}}==
<langsyntaxhighlight ATSlang="ats">#include
"share/atspre_staload.hats"
//
Line 2,119 ⟶ 2,431:
println! ("postorder:\t", postorder(t0));
println! ("level-order:\t", levelorder(t0));
end (* end of [main0] *)</langsyntaxhighlight>
 
{{out}}
Line 2,129 ⟶ 2,441:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">AddNode(Tree,1,2,3,1) ; Build global Tree
AddNode(Tree,2,4,5,2)
AddNode(Tree,3,6,0,3)
Line 2,181 ⟶ 2,493:
t .= i%Lev%, Lev++
Return t
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
function preorder(tree, node, res, child) {
if (node == "")
Line 2,274 ⟶ 2,586:
delete result
}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(
( tree
= 1
Line 2,317 ⟶ 2,629:
& out$("level-order:" levelorder$(!tree.))
&
)</langsyntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
manifest $(
VAL=0
LEFT=1
RIGHT=2
$)
 
let tree(v,l,r) = valof
$( let obj = getvec(2)
obj!VAL := v
obj!LEFT := l
obj!RIGHT := r
resultis obj
$)
 
let preorder(tree, cb) be unless tree=0
$( cb(tree!VAL)
preorder(tree!LEFT, cb)
preorder(tree!RIGHT, cb)
$)
 
let inorder(tree, cb) be unless tree=0
$( inorder(tree!LEFT, cb)
cb(tree!VAL)
inorder(tree!RIGHT, cb)
$)
 
let postorder(tree, cb) be unless tree=0
$( postorder(tree!LEFT, cb)
postorder(tree!RIGHT, cb)
cb(tree!VAL)
$)
 
let levelorder(tree, cb) be
$( let q=vec 255
let s=0 and e=1
q!0 := tree
until s=e do
$( unless q!s=0 do
$( q!e := q!s!LEFT
q!(e+1) := q!s!RIGHT
e := e+2
cb(q!s!VAL)
$)
s := s+1
$)
$)
 
let traverse(name, order, tree) be
$( let cb(n) be writef("%N ", n)
writef("%S:*T", name)
order(tree, cb)
wrch('*N')
$)
 
let start() be
$( let example = tree(1, tree(2, tree(4, tree(7, 0, 0), 0),
tree(5, 0, 0)),
tree(3, tree(6, tree(8, 0, 0),
tree(9, 0, 0)),
0))
traverse("preorder", preorder, example)
traverse("inorder", inorder, example)
traverse("postorder", postorder, example)
traverse("level-order", levelorder, example)
$)</syntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
 
Line 2,465 ⟶ 2,850:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 2,539 ⟶ 2,924:
Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal()));
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 2,546 ⟶ 2,931:
{{libheader|Boost|1.39.0}}
 
<langsyntaxhighlight lang="cpp">#include <boost/scoped_ptr.hpp>
#include <iostream>
#include <queue>
Line 2,639 ⟶ 3,024:
 
return 0;
}</langsyntaxhighlight>
 
===Array version===
<langsyntaxhighlight lang="cpp">#include <iostream>
 
using namespace std;
Line 2,710 ⟶ 3,095:
level_order(t);
cout << endl;
}</langsyntaxhighlight>
 
===Modern C++===
{{works with|C++14}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <memory>
#include <queue>
Line 2,808 ⟶ 3,193:
n.level_order(print);
std::cout << '\n';
}</langsyntaxhighlight>
 
{{out}}
Line 2,819 ⟶ 3,204:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">import ceylon.collection {
ArrayList
}
Line 2,915 ⟶ 3,300:
levelOrder(tree);
print("");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn walk [node f order]
(when node
(doseq [o order]
Line 2,961 ⟶ 3,346:
(print (format "%-12s" (str f ":")))
((resolve f) tree pr-node)
(println)))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">bintree = cluster [T: type] is leaf, node,
pre_order, post_order, in_order, level_order
branch = struct[left, right: bintree[T], val: T]
Line 3,057 ⟶ 3,442:
stream$puts(po, " " || int$unparse(i))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 3,065 ⟶ 3,450:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# In this example, we don't encapsulate binary trees as objects; instead, we have a
# convention on how to store them as arrays, and we namespace the functions that
Line 3,112 ⟶ 3,497:
test_walk "postorder"
test_walk "levelorder"
</syntaxhighlight>
</lang>
output
<langpre>
> coffee tree_traversal.coffee
preorder 1 2 4 7 5 3 6 8 9
Line 3,120 ⟶ 3,505:
postorder 7 4 5 2 8 9 6 3 1
levelorder 1 2 3 4 5 6 7 8 9
</langpre>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun preorder (node f)
(when node
(funcall f (first node))
Line 3,161 ⟶ 3,546:
(funcall traversal-function *tree* (lambda (value) (format t " ~A" value))))
 
(map nil #'show '(preorder inorder postorder level-order))</langsyntaxhighlight>
 
Output:
Line 3,172 ⟶ 3,557:
=={{header|Coq}}==
 
<langsyntaxhighlight lang="coq">Require Import Utf8.
Require Import List.
 
Line 3,181 ⟶ 3,566:
 
Fixpoint height (t: tree) : nat :=
1 + fold_left (λ? n t, max n (height t)) (children t) 0.
 
Example leaf n : tree := {| value := n ; children := nil |}.
Line 3,199 ⟶ 3,584:
match c with
| nil => n :: nil
| l :: r => inorder l ++ n :: flat_map inorder r
end.
 
Line 3,212 ⟶ 3,597:
| O => nil
| S fuel' =>
let '(p, f) := fold_right (λ? t r, let '(x, f) := r in (value t :: x, children t ++ f) ) (nil, nil) f in
p ++ levelorder_forest fuel' f
end.
Line 3,223 ⟶ 3,608:
Compute postorder t9.
Compute levelorder t9.
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
{{trans|C++}}
<langsyntaxhighlight lang="crystal">
class Node(T)
property left : Nil | Node(T)
Line 3,309 ⟶ 3,694:
puts
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,320 ⟶ 3,705:
=={{header|D}}==
This code is long because it's very generic.
<langsyntaxhighlight lang="d">import std.stdio, std.traits;
 
const final class Node(T) {
Line 3,396 ⟶ 3,781:
tree.levelOrder;
writeln;
}</langsyntaxhighlight>
{{out}}
<pre> preOrder: 1 2 4 7 5 3 6 8 9
Line 3,406 ⟶ 3,791:
{{trans|Haskell}}
Generic as the first version, but not lazy as the Haskell version.
<langsyntaxhighlight lang="d">const struct Node(T) {
T v;
Node* l, r;
Line 3,449 ⟶ 3,834:
writeln(postOrder(tree));
writeln(levelOrder(tree));
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 4, 7, 5, 3, 6, 8, 9]
Line 3,458 ⟶ 3,843:
===Alternative Lazy Version===
This version is not complete, it lacks the level order visit.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.string;
 
const struct Tree(T) {
Line 3,522 ⟶ 3,907:
tree.inOrder.map!(t => t.value).writeln;
tree.postOrder.map!(t => t.value).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 4, 7, 5, 3, 6, 8, 9]
[7, 4, 2, 5, 1, 8, 6, 9, 3]
[7, 4, 5, 2, 8, 9, 6, 3, 1]</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
 
{Structure holding node data}
 
type PNode = ^TNode;
TNode = record
Data: integer;
Left,Right: PNode;
end;
 
 
function PreOrder(Node: TNode): string;
{Recursively traverse Node-Left-Right}
begin
Result:=IntToStr(Node.Data);
if Node.Left<>nil then Result:=Result+' '+PreOrder(Node.Left^);
if Node.Right<>nil then Result:=Result+' '+PreOrder(Node.Right^);
end;
 
 
function InOrder(Node: TNode): string;
{Recursively traverse Left-Node-Right}
begin
Result:='';
if Node.Left<>nil then Result:=Result+inOrder(Node.Left^);
Result:=Result+IntToStr(Node.Data)+' ';
if Node.Right<>nil then Result:=Result+inOrder(Node.Right^);
end;
 
 
function PostOrder(Node: TNode): string;
{Recursively traverse Left-Right-Node}
begin
Result:='';
if Node.Left<>nil then Result:=Result+PostOrder(Node.Left^);
if Node.Right<>nil then Result:=Result+PostOrder(Node.Right^);
Result:=Result+IntToStr(Node.Data)+' ';
end;
 
 
function LevelOrder(Node: TNode): string;
{Traverse the tree at each level, Left to right}
var Queue: TList;
var NT: TNode;
begin
Queue:=TList.Create;
try
Result:='';
Queue.Add(@Node);
while true do
begin
{Display oldest node in queue}
NT:=PNode(Queue[0])^;
Queue.Delete(0);
Result:=Result+IntToStr(NT.Data)+' ';
{Queue left and right children}
if NT.left<>nil then Queue.add(NT.left);
if NT.right<>nil then Queue.add(NT.right);
if Queue.Count<1 then break;
end;
finally Queue.Free; end;
end;
 
 
procedure ShowBinaryTree(Memo: TMemo);
var Tree: array [0..9] of TNode;
var I: integer;
begin
{Fill array of node with data}
{that matchs its position in the array}
for I:=0 to High(Tree) do
begin
Tree[I].Data:=I+1;
Tree[I].Left:=nil;
Tree[I].Right:=nil;
end;
{Build the specified tree}
Tree[0].left:=@Tree[2-1];
Tree[0].right:=@Tree[3-1];
Tree[1].left:=@Tree[4-1];
Tree[1].right:=@Tree[5-1];
Tree[3].left:=@Tree[7-1];
Tree[2].left:=@Tree[6-1];
Tree[5].left:=@Tree[8-1];
Tree[5].right:=@Tree[9-1];
{Tranverse the tree in four specified ways}
Memo.Lines.Add('Pre-Order: '+PreOrder(Tree[0]));
Memo.Lines.Add('In-Order: '+InOrder(Tree[0]));
Memo.Lines.Add('Post-Order: '+PostOrder(Tree[0]));
Memo.Lines.Add('Level-Order: '+LevelOrder(Tree[0]));
end;
 
</syntaxhighlight>
{{out}}
<pre>
Pre-Order: 1 2 4 7 5 3 6 8 9
In-Order: 7 4 2 5 1 8 6 9 3
Post-Order: 7 4 5 2 8 9 6 3 1
Level-Order: 1 2 3 4 5 6 7 8 9
 
Elapsed Time: 4.897 ms.
 
</pre>
 
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">type
Node = struct {
int val;
*Node left, right;
},
Tree = *Node;
 
proc tree(int v; Tree l, r) Tree:
Tree t;
t := new(Node);
t*.val := v;
t*.left := l;
t*.right := r;
t
corp
 
proc preorder(Tree t) void:
if t /= nil then
write(t*.val, ' ');
preorder(t*.left);
preorder(t*.right)
fi
corp
 
proc inorder(Tree t) void:
if t /= nil then
inorder(t*.left);
write(t*.val, ' ');
inorder(t*.right)
fi
corp
 
proc postorder(Tree t) void:
if t /= nil then
postorder(t*.left);
postorder(t*.right);
write(t*.val, ' ')
fi
corp
 
proc levelorder(Tree t) void:
[256]Tree q;
word s, e;
s := 0;
q[s] := t;
e := 1;
while s /= e do
if q[s] /= nil then
q[e] := q[s]*.left;
q[e+1] := q[s]*.right;
e := e+2;
write(q[s]*.val, ' ')
fi;
s := s+1
od
corp
 
proc main() void:
Tree t;
t := tree(1,
tree(2,
tree(4,
tree(7,nil,nil),
nil),
tree(5,nil,nil)),
tree(3,
tree(6,
tree(8,nil,nil),
tree(9,nil,nil)),
nil));
 
write("preorder: "); preorder(t); writeln();
write("inorder: "); inorder(t); writeln();
write("postorder: "); postorder(t); writeln();
write("level-order: "); levelorder(t); writeln();
corp</syntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def btree := [1, [2, [4, [7, null, null],
null],
[5, null, null]],
Line 3,576 ⟶ 4,155:
print("level-order:")
levelOrder(btree, fn v { print(" ", v) })
println()</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight lang=easylang>
tree[] = [ 1 2 3 4 5 6 -1 7 -1 -1 -1 8 9 ]
#
proc preorder ind . .
if ind > len tree[] or tree[ind] = -1
return
.
write " " & tree[ind]
preorder ind * 2
preorder ind * 2 + 1
.
write "preorder:"
preorder 1
print ""
#
proc inorder ind . .
if ind > len tree[] or tree[ind] = -1
return
.
inorder ind * 2
write " " & tree[ind]
inorder ind * 2 + 1
.
write "inorder:"
inorder 1
print ""
#
proc postorder ind . .
if ind > len tree[] or tree[ind] = -1
return
.
postorder ind * 2
postorder ind * 2 + 1
write " " & tree[ind]
.
write "postorder:"
postorder 1
print ""
#
global tail head queue[] .
proc initqu n . .
len queue[] n
tail = 1
head = 1
.
proc enqu v . .
queue[tail] = v
tail = (tail + 1) mod1 len queue[]
.
func dequ .
if head = tail
return -1
.
h = head
head = (head + 1) mod1 len queue[]
return queue[h]
.
initqu len tree[]
proc levelorder n . .
enqu n
repeat
ind = dequ
until ind = -1
if ind < len tree[] and tree[ind] <> -1
write " " & tree[ind]
enqu ind * 2
enqu ind * 2 + 1
.
.
.
write "level-order:"
levelorder 1
print ""
</syntaxhighlight>
{{out}}
<pre>
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8
</pre>
 
=={{header|Eiffel}}==
Line 3,582 ⟶ 4,245:
 
Void-Safety has been disabled for simplicity of the code.
<langsyntaxhighlight lang="eiffel ">note
description : "Application for tree traversal demonstration"
output : "[
Line 3,632 ⟶ 4,295:
end
 
end -- class APPLICATION</langsyntaxhighlight>
<langsyntaxhighlight lang="eiffel ">note
description : "A simple node for a binary tree"
libraries : "Relies on LINKED_LIST from EiffelBase"
Line 3,759 ⟶ 4,422:
 
end
-- class NODE</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import extensions'routines;
import system'collections;
Line 3,775 ⟶ 4,438:
class Node
{
rprop int Value : rprop;
rprop Node Left : rprop;
rprop Node Right : rprop;
constructor new(int value)
Line 3,841 ⟶ 4,504:
LevelOrder = new Enumerable
{
Queue<Node> queue := class Queue<Node>.allocate(4).push:(self);
Enumerator enumerator() = new Enumerator
Line 3,847 ⟶ 4,510:
bool next() = queue.isNotEmpty();
get Value()
{
Node item := queue.pop();
Line 3,883 ⟶ 4,546:
console.printLine("Postorder :", tree.Postorder);
console.printLine("LevelOrder:", tree.LevelOrder)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,894 ⟶ 4,557:
=={{header|Elisa}}==
This is a generic component for binary tree traversals. More information about binary trees in Elisa are given in [http://jklunder.home.xs4all.nl/elisa/part02/doc030.html trees].
<syntaxhighlight lang="elisa">
<lang Elisa>
component BinaryTreeTraversals (Tree, Element);
type Tree;
Line 3,931 ⟶ 4,594:
];
end component BinaryTreeTraversals;
</syntaxhighlight>
</lang>
Tests
<syntaxhighlight lang="elisa">
<lang Elisa>
use BinaryTreeTraversals (Tree, integer);
 
Line 3,953 ⟶ 4,616:
{Item(Level_order(BT))}?
{ 1, 2, 3, 4, 5, 6, 7, 8, 9}
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Tree_Traversal do
defp tnode, do: {}
defp tnode(v), do: {:node, v, {}, {}}
Line 4,012 ⟶ 4,675:
end
 
Tree_Traversal.main</langsyntaxhighlight>
 
{{out}}
Line 4,023 ⟶ 4,686:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(tree_traversal).
-export([main/0]).
-export([preorder/2, inorder/2, postorder/2, levelorder/2]).
Line 4,064 ⟶ 4,727:
inorder(F, Tree), ?NEWLINE,
postorder(F, Tree), ?NEWLINE,
levelorder(F, Tree), ?NEWLINE.</langsyntaxhighlight>
 
Output:
Line 4,074 ⟶ 4,737:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">constant VALUE = 1, LEFT = 2, RIGHT = 3
 
constant tree = {1,
Line 4,140 ⟶ 4,803:
puts(1,"level-order: ")
level_order(tree)
puts(1,'\n')</langsyntaxhighlight>
 
Output:
Line 4,149 ⟶ 4,812:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
 
Line 4,223 ⟶ 4,886:
printf "\nlevel-order: "
levelorder tree |> Seq.iter show
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors combinators deques dlists fry io kernel
math.parser ;
IN: rosetta.tree-traversal
Line 4,297 ⟶ 4,960:
[ "levelorder: " write levelorder nl ]
[ "levelorder2: " write levelorder2 nl ]
} 2cleave ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">
class Tree
{
Line 4,370 ⟶ 5,033:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 4,381 ⟶ 5,044:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ binary tree (dictionary)
: node ( l r data -- node ) here >r , , , r> ;
: leaf ( data -- node ) 0 0 rot node ;
Line 4,436 ⟶ 5,099:
cr ' . tree postorder \ 7 4 5 2 8 9 6 3 1
cr tree max-depth . \ 4
cr ' . tree levelorder \ 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 4,446 ⟶ 5,109:
Otherwise, one can always write detailed code that gives effect to recursive usage, typically involving a variable called SP and an array called STACK. Oddly, such proceedings for the QuickSort algorithm are often declared to be "iterative", presumably because the absence of formally-declared recursive phrases blocks recognition of recursive action.
 
In the example source, the mainline, GORILLA, does its recursion via array twiddling and in that spirit, uses multiple lists for the "level" style traversal so that one tree clamber only need be made, whereas the recursive equivalent cheats by commanding one clamber for each level. The recursive routines store their state in part via the position within their code - that is, before, between, or after the recursive invocations, and are much easier to compare. Rather than litter the source with separate routines and their declarations for each of the four styles required, routine TARZAN has the four versions together for easy comparison, distinguished by a CASE statement. Actually, the code could be even more compact as in <langsyntaxhighlight Fortranlang="fortran">
IF (STYLE.EQ."PRE") CALL OUT(HAS)
IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE)
IF (STYLE.EQ."IN") CALL OUT(HAS)
IF (LINKR(HAS).GT.0) CALL TARZAN(LINKR(HAS),STYLE)
IF (STYLE.EQ."POST") CALL OUT(HAS)</langsyntaxhighlight>
But that would cloud the simplicity of each separate version, and would be extra messy with the fourth option included. On the other hand, the requirements for formal recursion carry the cost of the entry/exit protocol and moreover must do so for every invocation (though there is sometimes opportunity for end-recursion to be converted into a secret "go to") - avoiding this is why every invocation of TARZAN first checks that it has a live link, rather than coding this once only within TARZAN to return immediately when invoked with a dead link - whereas the array twiddling via SP deals only with what is required and notably, avoids raising the stack if it can. Further, the GORILLA version can if necessary maintain additional information, as is needed for the postorder traversal where, not having state information stored via position in the code (as with the recursive version) it needs to know whether it is returning to a node from which it departed via the rightwards link and so is in the post-traversal state and thus due a postorder action. This could involve an auxiliary array, but here is handled by taking advantage of the sign of the STACK element. This sort of trick might still be possible even if the link values were memory addresses rather than array indices, as many computers do not use their full word size for addressing.
 
Line 4,458 ⟶ 5,121:
Except for the usage of array MIST having an element zero and the use of an array assignment MIST(:,0) = 0, the GORILLA code is old-style Fortran. One could play tricks with EQUIVALENCE statements to arrange that an array's first element was at index zero, but that would rely on the absence of array bound checking and is more difficult with multi-dimensional arrays. Instead, one would make do either by having a separate list length variable, or else remembering the offsets... The MODULE usage requires F90 or later and provides a convenient protocol for global data, otherwise one must mess about with COMMON or parameter hordes. If that were done, the B6700 compiler would have handled it. But for the benefit of trembling modern compilers it also contains the fearsome new attribute, RECURSIVE, to flog the compilers into what was formalised for Algol in 1960 and was available ''for free'' via Burroughs in the 1970s.
 
On the other hand, the early-style Fortran DO-loop would always execute once, because the test was made only at the end of an iteration, and here, routine JANE does not know the value of MAXLEVEL until ''after'' the first iteration. Code such as <langsyntaxhighlight Fortranlang="fortran">
DO GASP = 1,MAXLEVEL
CALL TARZAN(1,HOW)
END DO</langsyntaxhighlight>
Would not work with modern Fortran, because the usual approach is to calculate the iteration count from the DO-loop parameters at the ''start'' of the DO-loop, and possibly not execute it at all if that count is not positive. This also means that with each iteration, the count must be decremented ''and'' the index variable adjusted; extra effort. There is no equivalent of Pascal's <code>Repeat ... until ''condition'';</code>, so, in place of a nice "structured" statement with clear interpretation, there is some messy code with a label and a GO TO, oh dear.
 
===Source===
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE ARAUCARIA !Cunning crosswords, also.
INTEGER ENUFF !To suit the set example.
Line 4,668 ⟶ 5,331:
CALL JANE("LEVEL") !Alternatively...
END !So much for that.
</syntaxhighlight>
</lang>
===Output===
Alternately GORILLA-style, and JANE-style:
Line 4,687 ⟶ 5,350:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#define NULL 0
 
Line 4,760 ⟶ 5,423:
Wend
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,772 ⟶ 5,435:
=={{header|FunL}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="funl">data Tree = Empty | Node( value, left, right )
 
def
Line 4,807 ⟶ 5,470:
println( inorder(tree) )
println( postorder(tree) )
println( levelorder(tree) )</langsyntaxhighlight>
 
{{out}}
Line 4,820 ⟶ 5,483:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Tree_traversal}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
Notice that the action to do when visiting a node is provided as a lambda expression:
In '''[https://formulae.org/?example=Tree_traversal this]''' page you can see the program(s) related to this task and their results.
 
[[File:Fōrmulæ - Tree traversal 01.png]]
 
[[File:Fōrmulæ - Tree traversal 02.png]]
 
[[File:Fōrmulæ - Tree traversal 03.png]]
 
[[File:Fōrmulæ - Tree traversal 04.png]]
 
'''Test case for pre-order'''
 
[[File:Fōrmulæ - Tree traversal 05.png]]
 
[[File:Fōrmulæ - Tree traversal 06.png]]
 
'''Test case for in-order'''
 
[[File:Fōrmulæ - Tree traversal 07.png]]
 
[[File:Fōrmulæ - Tree traversal 08.png]]
 
'''Test case for post-order'''
 
[[File:Fōrmulæ - Tree traversal 09.png]]
 
[[File:Fōrmulæ - Tree traversal 10.png]]
 
'''Test case for breadth-first search'''
 
[[File:Fōrmulæ - Tree traversal 11.png]]
 
[[File:Fōrmulæ - Tree traversal 12.png]]
 
=={{header|GFA Basic}}==
 
<syntaxhighlight lang="basic">
<lang>
maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
Line 4,945 ⟶ 5,640:
WEND
RETURN
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
Line 4,951 ⟶ 5,646:
{{trans|C}}
This is like many examples on this page.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 5,036 ⟶ 5,731:
func visitor(value int) {
fmt.Print(value, " ")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,046 ⟶ 5,741:
===Flat slice===
Alternative representation. Like Wikipedia [http://en.wikipedia.org/wiki/Binary_tree#Arrays Binary tree#Arrays]
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 5,116 ⟶ 5,811:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Uses Groovy '''Node''' and '''NodeBuilder''' classes
<langsyntaxhighlight lang="groovy">def preorder;
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
Line 5,154 ⟶ 5,849:
node
}
}</langsyntaxhighlight>
 
Verify that '''BinaryNodeBuilder''' will not allow a node to have more than 2 children
<langsyntaxhighlight lang="groovy">try {
new BinaryNodeBuilder().'1' {
a {}
Line 5,166 ⟶ 5,861:
} catch (org.codehaus.groovy.transform.powerassert.PowerAssertionError e) {
println 'limited to binary tree\r\n'
}</langsyntaxhighlight>
 
Test case #1 (from the task definition)
<langsyntaxhighlight lang="groovy">// 1
// / \
// 2 3
Line 5,185 ⟶ 5,880:
'6' { '8' {}; '9' {} }
}
}</langsyntaxhighlight>
 
Test case #2 (tests single right child)
<langsyntaxhighlight lang="groovy">// 1
// / \
// 2 3
Line 5,204 ⟶ 5,899:
'6' { '8' {}; '9' {} }
}
}</langsyntaxhighlight>
 
Run tests:
<langsyntaxhighlight lang="groovy">def test = { tree ->
println "preorder: ${preorder(tree).collect{it.name()}}"
println "preorder: ${tree.depthFirst().collect{it.name()}}"
Line 5,221 ⟶ 5,916:
}
test(tree1)
test(tree2)</langsyntaxhighlight>
 
Output:
Line 5,242 ⟶ 5,937:
=={{header|Haskell}}==
===Left Right nodes===
<langsyntaxhighlight lang="haskell">---------------------- TREE TRAVERSAL --------------------
 
data Tree a
Line 5,311 ⟶ 6,006:
([preorder, inorder, postorder, levelorder] <*> [tree])
where
justifyLeft n c s = take n (s <> replicate n c)</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 5,332 ⟶ 6,027:
 
{{Trans|Python}}
<syntaxhighlight lang ="haskell">import Data.TreeBool (Tree (..), drawForest, drawTree, foldTreebool)
import Data.Tree (Tree (..), drawForest, drawTree, foldTree)
 
---------------------- TREE TRAVERSAL --------------------
Line 5,365 ⟶ 6,061:
Int -> [Int] -> Int
nodeCount = const (succ . sum)
 
treeDepth = const (succ . foldr max 1)
 
treeMax x xs = maximum (x : xs)
 
treeMin x xs = minimum (x : xs)
 
treeProduct x xs = x * product xs
 
treeSum x xs = x + sum xs
 
treeWidth _ [] = 1
treeWidth _ xs = sum xs
 
treeLeaves :: Tree a -> [a]
treeLeaves = foldTree go
where
go (Node x []) = [x]
go (Node _ xs) = concat xs >>= go
 
--------------------------- TEST -------------------------
tree :: Tree Int
Line 5,424 ⟶ 6,114:
justifyLeft, justifyRight :: Int -> Char -> String -> String
justifyLeft n c s = take n (s <> replicate n c)
justifyRight n c = (drop . length) <*> (replicate n c <>)</langsyntaxhighlight>
<pre>1
|
Line 5,457 ⟶ 6,147:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
showTree(bTree, preorder|inorder|postorder|levelorder)
Line 5,488 ⟶ 6,178:
}
}
end</langsyntaxhighlight>
 
Output:
Line 5,500 ⟶ 6,190:
 
=={{header|Isabelle}}==
<langsyntaxhighlight Isabellelang="isabelle">theory Tree
imports Main
begin
Line 5,507 ⟶ 6,197:
 
definition example :: "int tree" where
"example =
Node
(Node
Line 5,529 ⟶ 6,219:
)"
 
fun preorder :: "'a tree ? 'a list" where
"preorder Leaf = []"
| "preorder (Node l a r) = a # preorder l @ preorder r"
Line 5,535 ⟶ 6,225:
lemma "preorder example = [1, 2, 4, 7, 5, 3, 6, 8, 9]" by code_simp
 
fun inorder :: "'a tree ? 'a list" where
"inorder Leaf = []"
| "inorder (Node l a r) = inorder l @ [a] @ inorder r"
Line 5,541 ⟶ 6,231:
lemma "inorder example = [7, 4, 2, 5, 1, 8, 6, 9, 3]" by code_simp
 
fun postorder :: "'a tree ? 'a list" where
"postorder Leaf = []"
| "postorder (Node l a r) = postorder l @ postorder r @ [a]"
Line 5,561 ⟶ 6,251:
so we provide some help by defining what the size of a tree is.
fun tree_size :: "'a tree ? nat" where
"tree_size Leaf = 1"
| "tree_size (Node l _ r) = 1 + tree_size l + tree_size r"
 
function (sequential) bfs :: "'a tree list ? 'a list" where
"bfs [] = []"
| "bfs (Leaf#q) = bfs q"
Line 5,571 ⟶ 6,261:
by pat_completeness auto
termination bfs
by(relation "measure (λqs?qs. sum_list (map tree_size qs))") simp+
 
fun levelorder :: "'a tree ? 'a list" where
"levelorder t = bfs [t]"
 
lemma "levelorder example = [1, 2, 3, 4, 5, 6, 7, 8, 9]" by code_simp
 
end</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">preorder=: ]S:0
postorder=: ([:; postorder&.>@}.) , >@{.
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
inorder=: ([:; inorder&.>@(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}.</langsyntaxhighlight>
 
Required example:
 
<langsyntaxhighlight Jlang="j">N2=: conjunction def '(<m),(<n),<y'
N1=: adverb def '(<m),<y'
L=: adverb def '<m'
 
tree=: 1 N2 (2 N2 (4 N1 (7 L)) 5 L) 3 N1 6 N2 (8 L) 9 L</langsyntaxhighlight>
 
This tree is organized in a pre-order fashion
 
<langsyntaxhighlight Jlang="j"> preorder tree
1 2 4 7 5 3 6 8 9</langsyntaxhighlight>
 
post-order is not that much different from pre-order, except that the children must extracted before the parent.
 
<langsyntaxhighlight Jlang="j"> postorder tree
7 4 5 2 8 9 6 3 1</langsyntaxhighlight>
 
Implementing in-order is more complex because we must sometimes test whether we have any leaves, instead of relying on J's implicit looping over lists
 
<langsyntaxhighlight Jlang="j"> inorder tree
7 4 2 5 1 8 6 9 3</langsyntaxhighlight>
 
level-order can be accomplished by constructing a map of the locations of the leaves, sorting these map locations by their non-leaf indices and using the result to extract all leaves from the tree. Elements at the same level with the same parent will have the same sort keys and thus be extracted in preorder fashion, which works just fine.
 
<langsyntaxhighlight Jlang="j"> levelorder tree
1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
 
For J novices, here's the tree instance with a few redundant parenthesis:
 
<langsyntaxhighlight Jlang="j"> tree=: 1 N2 (2 N2 (4 N1 (7 L)) (5 L)) (3 N1 (6 N2 (8 L) (9 L)))</langsyntaxhighlight>
 
Syntactically, N2 is a binary node expressed as <code>m N2 n y</code>. N1 is a node with a single child, expressed as <code>m N2 y</code>. L is a leaf node, expressed as <code>m L</code>. In all three cases, the parent value (<code>m</code>) for the node appears on the left, and the child tree(s) appear on the right. (And <code>n</code> must be parenthesized if it is not a single word.)
Line 5,626 ⟶ 6,316:
Of course, there are other ways of representing tree structures in J. One fairly natural approach pairs a list of data with a matching list of parent indices. For example:
 
<langsyntaxhighlight Jlang="j">example=:1 8 3 4 7 5 9 6 2,: 0 7 0 8 3 8 7 2 0</langsyntaxhighlight>
 
Here, we have two possible ways of identifying the root node. It can be in a known place in the list (index 0, for this example). But it is also the only node which is its own parent. For this task we'll use the more general (and thus slower) approach which allows us to place the root node anywhere in the sequence.
Line 5,632 ⟶ 6,322:
Next, let's define a few utilities:
 
<langsyntaxhighlight Jlang="j">depth=: +/@((~: , (~: i.@#@{.)~) {:@,)@({~^:a:)
 
reorder=:4 :0
Line 5,644 ⟶ 6,334:
parent=:3 :'parent[''data parent''=. y'
 
childinds=: [: <:@(2&{.@-.&> #\) (</. #\)`(]~.)`(a:"0)}~</langsyntaxhighlight>
 
Here, <code>data</code> extracts the list of data items from the tree and <code>parent</code> extracts the structure from the tree.
Line 5,656 ⟶ 6,346:
Next, we define our "traversal" routines (actually, we are going a bit overboard here - we really only need to extract the data for this tasks's concept of traversal):
 
<langsyntaxhighlight Jlang="j">dataorder=: /:@data reorder ]
levelorder=: /:@depth@parent reorder ]
 
Line 5,708 ⟶ 6,398:
todo=. todo,|.ch end. end.
r
)</langsyntaxhighlight>
 
These routines assume that children of a node are arranged so that the lower index appears to the left of the higher index. If instead we wanted to rely on the ordering of their values, we could first use <code>dataorder</code> to enforce the assumption that child indexes are ordered properly.
Line 5,714 ⟶ 6,404:
Example use:
 
<langsyntaxhighlight Jlang="j"> levelorder dataorder example
1 2 3 4 5 6 7 8 9
0 0 0 1 1 2 3 5 5
Line 5,725 ⟶ 6,415:
postorder dataorder example
7 4 5 2 8 9 6 3 1
1 3 3 8 6 6 7 8 8</langsyntaxhighlight>
 
(Once again, all we really need for this task is the first row of those results - the part that represents data.)
Line 5,737 ⟶ 6,427:
 
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.*;
 
public class TreeTraversal {
Line 5,823 ⟶ 6,513:
}
}</langsyntaxhighlight>
Output:
<pre>1 2 4 7 5 3 6 8 9
Line 5,838 ⟶ 6,528:
 
{{works with|Java|1.8+}}
<langsyntaxhighlight lang="java5">import java.util.function.Consumer;
import java.util.Queue;
import java.util.LinkedList;
Line 5,963 ⟶ 6,653:
System.out.println();
}
}</langsyntaxhighlight>
 
Output:
Line 5,975 ⟶ 6,665:
====Iteration====
inspired by [[#Ruby|Ruby]]
<langsyntaxhighlight lang="javascript">function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
Line 6,014 ⟶ 6,704:
print("*** inorder ***"); tree.inorder(print);
print("*** postorder ***"); tree.postorder(print);
print("*** levelorder ***"); tree.levelorder(print);</langsyntaxhighlight>
 
====Functional composition====
Line 6,020 ⟶ 6,710:
(for binary trees consisting of nested lists)
 
<langsyntaxhighlight lang="javascript">(function () {
 
function preorder(n) {
Line 6,108 ⟶ 6,798:
return wikiTable(lstTest, true) + '\n\n' + JSON.stringify(lstTest);
 
})();</langsyntaxhighlight>
 
Output:
Line 6,125 ⟶ 6,815:
|}
 
<langsyntaxhighlight JavaScriptlang="javascript">[["Traversal","Nodes visited"],
["preorder",[1,2,4,7,5,3,6,8,9]],["inorder",[7,4,2,5,1,8,6,9,3]],
["postorder",[7,4,5,2,8,9,6,3,1]],["levelorder",[1,2,3,4,5,6,7,8,9]]]</langsyntaxhighlight>
 
 
Line 6,137 ⟶ 6,827:
 
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 6,257 ⟶ 6,947:
}, {});
 
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">{"preorder":[1, 2, 4, 7, 5, 3, 6, 8, 9],
"inorder":[7, 4, 2, 5, 1, 8, 6, 9, 3],
"postorder":[7, 4, 5, 2, 8, 9, 6, 3, 1],
"level-order":[1, 2, 3, 4, 5, 6, 7, 8, 9]}</langsyntaxhighlight>
 
===ES6===
Line 6,268 ⟶ 6,958:
{{Trans|Haskell}}
{{Trans|Python}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 6,314 ⟶ 7,004:
// task: 'Visualize a tree'
console.log([
" + 4 - 7",
" + 2 ¦",
" ¦ + 5",
" 1 ¦",
" ¦ + 8",
" + 3 - 6 ¦",
" + 9"
].join("\n"));
 
Line 6,395 ⟶ 7,085:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre> + 4 - 7
+ 2 ¦
¦ + 5
1 ¦
¦ + 8
+ 3 - 6 ¦
+ 9
preorder: 1,2,4,7,5,3,6,8,9
inorder: 7,4,2,5,1,8,6,9,3
Line 6,413 ⟶ 7,103:
 
The implementation assumes an array structured recursively as [ node, left, right ], where "left" and "right" may be [] or null equivalently.
<langsyntaxhighlight lang="jq">def preorder:
if length == 0 then empty
else .[0], (.[1]|preorder), (.[2]|preorder)
Line 6,439 ⟶ 7,129:
 
def levelorder: [.] | recurse( tails ) | heads;
</syntaxhighlight>
</lang>
'''The task''':
<langsyntaxhighlight lang="jq">def task:
# [node, left, right]
def atree: [1, [2, [4, [7,[],[]],
Line 6,457 ⟶ 7,147:
;
 
task</langsyntaxhighlight>
{{Out}}
$ jq -n -c -r -f Tree_traversal.jq
Line 6,466 ⟶ 7,156:
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">tree = Any[1, Any[2, Any[4, Any[7, Any[],
Any[]],
Any[]],
Line 6,492 ⟶ 7,182:
t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t)
end
</syntaxhighlight>
</lang>
 
{{Out}}
Line 6,507 ⟶ 7,197:
=={{header|Kotlin}}==
===procedural style===
<langsyntaxhighlight lang="scala">data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = "$v"
}
Line 6,573 ⟶ 7,263:
exec(" postOrder: ", nodes[1], ::postOrder)
exec("level-order: ", nodes[1], ::levelOrder)
}</langsyntaxhighlight>
 
{{Out}}
Line 6,584 ⟶ 7,274:
 
===object-oriented style===
<langsyntaxhighlight lang="scala">fun main(args: Array<String>) {
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = " $v"
Line 6,625 ⟶ 7,315:
exec("level-order:", Node::levelOrder)
}
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
Line 6,638 ⟶ 7,328:
- {A.get index array} gets the value of array at index
</pre>
<langsyntaxhighlight lang="scheme">
{def walk
 
Line 6,673 ⟶ 7,363:
{sort < {T}} -> 1 2 3 4 5 6 7 8 9
{sort > {T}} -> 9 8 7 6 5 4 3 2 1
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- parent script "BinaryTreeNode"
 
property _val, _left, _right
Line 6,703 ⟶ 7,393:
on getRight (me)
return me._right
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">-- parent script "BinaryTreeTraversal"
 
on inOrder (me, node, l)
Line 6,755 ⟶ 7,445:
delete the last char of str
return str
end</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lingo">-- create the tree
l = []
repeat with i = 1 to 10
Line 6,777 ⟶ 7,467:
put "inorder: " & trav.serialize(trav.inOrder(l[1]))
put "postorder: " & trav.serialize(trav.postOrder(l[1]))
put "level-order: " & trav.serialize(trav.levelOrder(l[1]))</langsyntaxhighlight>
 
{{Out}}
Line 6,788 ⟶ 7,478:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">; nodes are [data left right], use "first" to get data
 
to node.left :node
Line 6,844 ⟶ 7,534:
in.order :tree [(type ? "| |)] (print)
post.order :tree [(type ? "| |)] (print)
level.order :tree [(type ? "| |)] (print)</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">
:- object(tree_traversal).
 
Line 6,928 ⟶ 7,618:
 
:- end_object.
</syntaxhighlight>
</lang>
Sample output:
<langsyntaxhighlight lang="text">
| ?- ?- tree_traversal::orders.
Pre-order: 1 2 4 7 5 3 6 8 9
Line 6,937 ⟶ 7,627:
Level-order: 1 2 3 4 5 6 7 8 9
yes
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">
<lang Lua>-- Utility
local function appenddepth_first(t1tr, t2a, b, c, flat_list)
for _, vval in ipairs(t2{a, b, c}) do
if type(tr[val]) == "table" then
table.insert(t1, v)
depth_first(tr[val], a, b, c, flat_list)
end
elseif type(tr[val]) ~= "nil" then
end
table.insert(flat_list, tr[val])
 
end -- if
-- Node class
end -- for
local Node = {}
return flat_list
Node.__index = Node
 
function Node:order(order)
local r = {}
append(r, type(self[order[1]]) == "table" and self[order[1]]:order(order) or {self[order[1]]})
append(r, type(self[order[2]]) == "table" and self[order[2]]:order(order) or {self[order[2]]})
append(r, type(self[order[3]]) == "table" and self[order[3]]:order(order) or {self[order[3]]})
return r
end
 
function Node:levelorder()
local levelorder = {}
local queue = {self}
while next(queue) do
local node = table.remove(queue, 1)
table.insert(levelorder, node[1])
table.insert(queue, node[2])
table.insert(queue, node[3])
end
return levelorder
end
local function flatten_pre_order(tr) return depth_first(tr, 1, 2, 3, {}) end
local function flatten_in_order(tr) return depth_first(tr, 2, 1, 3, {}) end
local function flatten_post_order(tr) return depth_first(tr, 2, 3, 1, {}) end
 
local function flatten_level_order(tr)
-- Node creator
local flat_list, queue = {}, {tr}
local function new(value, left, right)
while next(queue) do -- while queue is not empty
return value and setmetatable({
local node = table.remove(queue, 1) -- dequeue
value,
if (type(leftnode) == "table") and new(unpack(left)) or new(left),then
table.insert(flat_list, node[1])
(type(right) == "table") and new(unpack(right)) or new(right),
table.insert(queue, node[2]) -- enqueue
}, Node) or nil
table.insert(queue, node[3]) -- enqueue
else
table.insert(flat_list, node)
end -- if
end -- while
return flat_list
end
 
-- Example
local tree = new({1, {2, {4, 7}, 5}, {3, {6, 8, 9}})}
print("preorderPre order: " .. table.concat(flatten_pre_order(tree:order({1, 2, 3}), " "))
print("inorderIn order: " .. table.concat(flatten_in_order(tree:order({2, 1, 3}), " "))
print("postorderPost order: " .. table.concat(flatten_post_order(tree:order({2, 3, 1}), " "))
print("level-Level order: " .. table.concat(tree:levelorderflatten_level_order(tree), " "))</lang>
</syntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 6,991 ⟶ 7,672:
A tuple is an "auto array" in M2000 Interpreter. (,) is the zero length array.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Null=(,)
Line 7,051 ⟶ 7,732:
}
CheckIt
</syntaxhighlight>
</lang>
===Using OOP===
Now tree is nodes with pointers to nodes (a node ifs a Group, the user object)
The "as pointer" is optional, but we can use type check if we want.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,140 ⟶ 7,821:
}
OOP
</syntaxhighlight>
</lang>
 
or we can put modules inside Node Class as methods
also i put a visitor as a call back (a lambda function called as module)
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,232 ⟶ 7,913:
}
OOP
</syntaxhighlight>
</lang>
 
Using Event object as visitor
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,327 ⟶ 8,008:
}
OOP
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,338 ⟶ 8,019:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">preorder[a_Integer] := a;
preorder[a_[b__]] := Flatten@{a, preorder /@ {b}};
inorder[a_Integer] := a;
Line 7,346 ⟶ 8,027:
levelorder[a_] :=
Flatten[Table[Level[a, {n}], {n, 0, Depth@a}]] /. {b_Integer[__] :>
b};</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="mathematica">preorder[1[2[4[7], 5], 3[6[8, 9]]]]
inorder[1[2[4[7], 5], 3[6[8, 9]]]]
postorder[1[2[4[7], 5], 3[6[8, 9]]]]
levelorder[1[2[4[7], 5], 3[6[8, 9]]]]</langsyntaxhighlight>
{{out}}
<pre>{1, 2, 4, 7, 5, 3, 6, 8, 9}
Line 7,360 ⟶ 8,041:
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module tree_traversal.
:- interface.
 
Line 7,452 ⟶ 8,133:
print_value(V, !IO) :-
io.print(V, !IO),
io.write_string(" ", !IO).</langsyntaxhighlight>
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 7,458 ⟶ 8,139:
postorder: 7 4 5 2 8 9 6 3 1
levelorder: 1 2 3 4 5 6 7 8 9 </pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay [show (f example)
| f <- [preorder,inorder,postorder,levelorder]])]
 
example :: tree num
example = Node 1 (Node 2 (Node 4 (leaf 7) Nilt)
(leaf 5))
(Node 3 (Node 6 (leaf 8) (leaf 9)) Nilt)
 
tree * ::= Nilt | Node * (tree *) (tree *)
 
leaf :: *->tree *
leaf k = Node k Nilt Nilt
 
preorder :: tree *->[*]
preorder Nilt = []
preorder (Node v l r) = v : preorder l ++ preorder r
 
inorder :: tree *->[*]
inorder Nilt = []
inorder (Node v l r) = inorder l ++ v : inorder r
 
postorder :: tree *->[*]
postorder Nilt = []
postorder (Node v l r) = postorder l ++ postorder r ++ [v]
 
levelorder :: tree *->[*]
levelorder t = f [t]
where f [] = []
f (Nilt:xs) = f xs
f (Node v l r:xs) = v : f (xs++[l,r])</syntaxhighlight>
{{out}}
<pre>[1,2,4,7,5,3,6,8,9]
[7,4,2,5,1,8,6,9,3]
[7,4,5,2,8,9,6,3,1]
[1,2,3,4,5,6,7,8,9]</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import deques
 
type
Line 7,504 ⟶ 8,223:
echo inorder tree
echo postorder tree
echo levelorder tree</langsyntaxhighlight>
 
{{out}}
Line 7,513 ⟶ 8,232:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use??use Collection;
 
class Test {
Line 7,626 ⟶ 8,345:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 7,637 ⟶ 8,356:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">type 'a tree = Empty
| Node of 'a * 'a tree * 'a tree
 
Line 7,686 ⟶ 8,405:
inorder (Printf.printf "%d ") tree; print_newline ();
postorder (Printf.printf "%d ") tree; print_newline ();
levelorder (Printf.printf "%d ") tree; print_newline ()</langsyntaxhighlight>
Output:
<pre>1 2 4 7 5 3 6 8 9
Line 7,695 ⟶ 8,414:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: Tree(v, l, r)
 
Tree method: initialize(v, l, r) v := v l := l r := r ;
Line 7,725 ⟶ 8,444:
n l dup ifNotNull: [ c send ] drop
n r dup ifNotNull: [ c send ] drop
] ;</langsyntaxhighlight>
 
{{out}}
Line 7,748 ⟶ 8,467:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
one = .Node~new(1);
two = .Node~new(2);
Line 7,832 ⟶ 8,551:
nodequeue~queue(next~right)
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 7,842 ⟶ 8,561:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
Tree = n(1
n(2
Line 7,899 ⟶ 8,618:
{Show {Inorder Tree}}
{Show {Postorder Tree}}
{Show {Levelorder Tree}}</langsyntaxhighlight>
 
=={{header|Perl}}==
Tree nodes are represented by 3-element arrays: [0] - the value; [1] - left child; [2] - right child.
<langsyntaxhighlight lang="perl">sub preorder
{
my $t = shift or return ();
Line 7,938 ⟶ 8,657:
print "in: @{[inorder($x)]}\n";
print "post: @{[postorder($x)]}\n";
print "depth: @{[depth($x)]}\n";</langsyntaxhighlight>
Output:
<pre>pre: 1 2 4 7 5 3 6 8 9
Line 7,950 ⟶ 8,669:
This is included in the distribution as demo\rosetta\Tree_traversal.exw, which also contains a way to build such a nested structure, and thirdly a "flat list of nodes" tree, that allows more interesting options such as a tag sort.
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">VALUE</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">LEFT</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">RIGHT</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span>
Line 7,997 ⟶ 8,716:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n postorder: "</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">postorder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n level-order: "</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">level_order</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tree</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 8,008 ⟶ 8,727:
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">class Node {
private $left;
private $right;
Line 8,109 ⟶ 8,828:
$tree->postOrder($arr[1]);
echo "\nlevel-order:\t";
$tree->levelOrder($arr[1]);</langsyntaxhighlight>
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,117 ⟶ 8,836:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de preorder (Node Fun)
(when Node
(Fun (car Node))
Line 8,150 ⟶ 8,869:
(prin (align -13 (pack Order ":")))
(Order *Tree printsp)
(prinl) )</langsyntaxhighlight>
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,159 ⟶ 8,878:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">tree :-
Tree= [1,
[2,
Line 8,215 ⟶ 8,934:
 
append_dl(X-Y, Y-Z, X-Z).
</syntaxhighlight>
</lang>
Output :
<pre>?- tree.
Line 8,227 ⟶ 8,946:
=={{header|PureBasic}}==
{{works with|PureBasic|4.5+}}
<langsyntaxhighlight PureBasiclang="purebasic">Structure node
value.i
*left.node
Line 8,361 ⟶ 9,080:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,372 ⟶ 9,091:
===Python: Procedural===
 
<langsyntaxhighlight lang="python">from collections import namedtuple
Node = namedtuple('Node', 'data, left, right')
Line 8,443 ⟶ 9,162:
print(f"{traversal.__name__:>{w}}:", end=' ')
traversal(tree)
print()</langsyntaxhighlight>
 
'''Sample output:'''
Line 8,459 ⟶ 9,178:
 
Subclasses a namedtuple adding traversal methods that apply a visitor function to data at nodes of the tree in order
<langsyntaxhighlight lang="python">from collections import namedtuple
from sys import stdout
Line 8,519 ⟶ 9,238:
stdout.write('\nlevelorder: ')
tree.levelorder(printwithspace)
stdout.write('\n')</langsyntaxhighlight>
 
{{out}}
Line 8,536 ⟶ 9,255:
This level of abstraction and reuse brings real efficiencies – the short and easily-written '''foldTree''', for example, doesn't just traverse and list contents in flexible orders - we can pass any kind of accumulation or tree-transformation to it.
 
<langsyntaxhighlight lang="python">'''Tree traversals'''
 
from itertools import chain
Line 8,746 ⟶ 9,465:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Tree traversals - accumulating and folding:
Line 8,763 ⟶ 9,482:
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang qi>
(set *tree* [1 [2 [4 [7]]
[5]]
Line 8,808 ⟶ 9,527:
(inorder (value *tree*))
(levelorder (value *tree*))
</syntaxhighlight>
</lang>
 
Output:
Line 8,818 ⟶ 9,537:
=={{header|Quackery}}==
 
Requires the words at [[Queue/Definition#Quackery]] for <code>level-order</code>.
<lang Quackery>
 
[ this ] is nil ( --> [ )
<syntaxhighlight lang="quackery"> [ this ] is nil ( --> [ )
 
[ ' [ 1
[ 2
[ 4
[ 7 nil nil ]
nil ]
[ 5 nil nil ] ]
[ 3
[ 6
[ 8 nil nil ]
[ 9 nil nil ] ]
nil ] ] ] is tree ( --> [ )
 
[ dup nil = iff drop done
Line 8,839 ⟶ 9,559:
recurse ] is pre-order ( [ --> )
 
[ dup nil = iff drop done
unpack unrot
recurse
Line 8,851 ⟶ 9,571:
echo sp ] is post-order ( [ --> )
 
[ queue swap push
[ stack [ ] ] is queue ( --> s )
[ dup empty?
 
iff drop done
[ queue share [] = ] is qempty ( --> b )
pop
 
dup nil = iff
[ queue take
swap nested join
queue put ] is enqueue ( x --> )
 
[ queue take
behead swap
queue put ] is dequeue ( --> x )
 
[ enqueue
[ qempty not while
dequeue
dup nil = iff
drop again
unpack swap
enqueuerot echo sp
enqueuedip push push
echo sp again ] ] is level-order ( [ --> )
 
tree pre-order cr
tree in-order cr
tree post-order cr
tree level-order cr</langsyntaxhighlight>
 
{{out}}
Line 8,883 ⟶ 9,592:
7 4 2 5 1 8 6 9 3
7 4 5 2 8 9 6 3 1
1 2 3 4 5 6 7 8 9 </pre>
</pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 8,911 ⟶ 9,619:
(define (run order)
(printf "~a:" (object-name order))
(order the-tree (λ?(x) (printf " ~s" x)))
(newline))
(for-each run (list preorder inorder postorder levelorder))
</syntaxhighlight>
</lang>
 
Output:
Line 8,926 ⟶ 9,634:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>class TreeNode {
has TreeNode $.parent;
has TreeNode $.left;
Line 8,983 ⟶ 9,691:
say "inorder: ",$root.in-order.join(" ");
say "postorder: ",$root.post-order.join(" ");
say "levelorder:",$root.level-order.join(" ");</langsyntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,989 ⟶ 9,697:
postorder: 7 4 5 2 8 9 6 3 1
levelorder:1 2 3 4 5 6 7 8 9</pre>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
; "compacted" version
tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]]
 
visit: func [tree [block!]][prin rejoin [first tree " "]]
left: :second
right: :third
 
preorder: func [tree [block!]][
if not empty? tree [visit tree]
attempt [preorder left tree]
attempt [preorder right tree]
]
prin "preorder: " preorder tree
print ""
 
inorder: func [tree [block!]][
attempt [inorder left tree]
if not empty? tree [visit tree]
attempt [inorder right tree]
]
prin "inorder: " inorder tree
print ""
 
postorder: func [tree [block!]][
attempt [postorder left tree]
attempt [postorder right tree]
if not empty? tree [visit tree]
]
prin "postorder: " postorder tree
print ""
 
queue: []
enqueue: func [tree [block!]][append/only queue tree]
dequeue: func [queue [block!]][take queue]
level-order: func [tree [block!]][
clear head queue
queue: enqueue tree
while [not empty? queue] [
tree: dequeue queue
if not empty? tree [visit tree]
attempt [enqueue left tree]
attempt [enqueue right tree]
]
]
prin "level-order: " level-order tree
</syntaxhighlight>
{{out}}
<pre>
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Show Preorder <Tree>>
<Show Inorder <Tree>>
<Show Postorder <Tree>>
<Show Levelorder <Tree>>;
};
 
Show {
s.F t.T = <Prout s.F ': ' <Mu s.F t.T>>;
};
 
Tree {
= (1 (2 (4 (7 () ()) ()) (5 () ())) (3 (6 (8 () ()) (9 () ())) ()));
};
 
Preorder {
() = ;
(s.V t.L t.R) = s.V <Preorder t.L> <Preorder t.R>;
};
 
Inorder {
() = ;
(s.V t.L t.R) = <Inorder t.L> s.V <Inorder t.R>;
};
 
Postorder {
() = ;
(s.V t.L t.R) = <Postorder t.L> <Postorder t.R> s.V;
};
 
Levelorder {
= ;
() e.Q = <Levelorder e.Q>;
(s.V t.L t.R) e.Q = s.V <Levelorder e.Q t.L t.R>;
};</syntaxhighlight>
{{out}}
<pre>Preorder : 1 2 4 7 5 3 6 8 9
Inorder : 7 4 2 5 1 8 6 9 3
Postorder : 7 4 5 2 8 9 6 3 1
Levelorder : 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* Tree traversal
Line 9,309 ⟶ 10,116:
Say ''
End
Return</langsyntaxhighlight>
{{out}}
<pre> 1
Line 9,325 ⟶ 10,132:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">BinaryTreeNode = Struct.new(:value, :left, :right) do
def self.from_array(nested_list)
value, left, right = nested_list
Line 9,364 ⟶ 10,171:
root.send(mthd) {|node| print "#{node.value} "}
puts
end</langsyntaxhighlight>
 
{{out}}
Line 9,375 ⟶ 10,182:
=={{header|Rust}}==
This solution uses iteration (rather than recursion) for all traversal types.
<syntaxhighlight lang="rust">
<lang Rust>
#![feature(box_syntax, box_patterns)]
 
Line 9,551 ⟶ 10,358:
}
}
</syntaxhighlight>
</lang>
Output is same as Ruby et al.
 
=={{header|Scala}}==
{{works with|Scala|2.11.x}}
<langsyntaxhighlight Scalalang="scala">case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) {
 
def preorder(f: IntNode => Unit) {
Line 9,610 ⟶ 10,417:
println(s)
}
}</langsyntaxhighlight>
 
Output:<pre>
Line 9,618 ⟶ 10,425:
levelorder: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">(define (preorder tree)
(if (null? tree)
'()
(append (list (car tree))
(preorder (cadr tree))
(preorder (caddr tree)))))
 
(define (inorder tree)
(if (null? tree)
'()
(append (inorder (cadr tree))
(list (car tree))
(inorder (caddr tree)))))
 
(define (postorder tree)
(if (null? tree)
'()
(append (postorder (cadr tree))
(postorder (caddr tree))
(list (car tree)))))
 
(define (level-order tree)
(define lst '())
(define (traverse nodes)
(if (pair? nodes)
(let ((next-nodes '()))
(do ((p nodes (cdr p)))
((null? p))
(set! lst (cons (caar p) lst))
(let* ((n '())
(n (if (null? (cadar p))
n
(cons (cadar p) n)))
(n (if (null? (caddar p))
n
(cons (caddar p) n))))
(set! next-nodes (append n next-nodes))))
(traverse (reverse next-nodes)))))
(if (null? tree)
'()
(begin
(traverse (list tree))
(reverse lst))))
 
(define (demonstration tree)
(define (display-values lst)
(do ((p lst (cdr p)))
((null? p))
(display (car p))
(if (pair? (cdr p))
(display " ")))
(newline))
(display "preorder: ") (display-values (preorder tree))
(display "inorder: ") (display-values (inorder tree))
(display "postorder: ") (display-values (postorder tree))
(display "level-order: ") (display-values (level-order tree)))
 
(define the-task-tree
'(1 (2 (4 (7 () ())
())
(5 () ()))
(3 (6 (8 () ())
(9 () ()))
())))
 
(demonstration the-task-tree)</syntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">
<lang sequenceL>
main(args(2)) :=
"preorder: " ++ toString(preOrder(testTree)) ++
Line 9,663 ⟶ 10,543:
)
);
</syntaxhighlight>
</lang>
{{out}}
Output:
Line 9,672 ⟶ 10,552:
level-order: [1,2,3,4,5,6,7,8,9]
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program tree_traversal;
tree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]];
 
print("preorder ", preorder(tree));
print("inorder ", inorder(tree));
print("postorder ", postorder(tree));
print("level-order ", levelorder(tree));
 
proc preorder(tree);
if tree = om then return []; end if;
[item, left, right] := tree;
return [item] + preorder(left) + preorder(right);
end proc;
 
proc inorder(tree);
if tree = om then return []; end if;
[item, left, right] := tree;
return inorder(left) + [item] + inorder(right);
end proc;
 
proc postorder(tree);
if tree = om then return []; end if;
[item, left, right] := tree;
return postorder(left) + postorder(right) + [item];
end proc;
 
proc levelorder(tree);
items := [];
loop init queue := [tree]; while queue /= [] do
[item, left, right] fromb queue;
items with:= item;
if left /= om then queue with:= left; end if;
if right /= om then queue with:= right; end if;
end loop;
return items;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>preorder [1 2 4 7 5 3 6 8 9]
inorder [7 4 2 5 1 8 6 9 3]
postorder [7 4 5 2 8 9 6 3 1]
level-order [1 2 3 4 5 6 7 8 9]</pre>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func preorder(t) {
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
}
Line 9,702 ⟶ 10,626:
say "in: #{inorder(x)}";
say "post: #{postorder(x)}";
say "depth: #{depth(x)}";</langsyntaxhighlight>
{{out}}
<pre>
Line 9,721 ⟶ 10,645:
 
'''Object subclass: EmptyNode'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
EmptyNode>>accept: aVisitor
 
Line 9,730 ⟶ 10,654:
EmptyNode>>traverse: aVisitorClass do: aBlock
^self accept: (aVisitorClass block: aBlock)
</syntaxhighlight>
</lang>
 
'''EmptyNode subclass: Node'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
Node>>accept: aVisitor
^aVisitor visit: self
Line 9,768 ⟶ 10,692:
Node class>>data: anObject
^self new data: anObject
</syntaxhighlight>
</lang>
 
'''Object subclass: Visitor'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
visit: aNode
self subclassResponsibility
Line 9,788 ⟶ 10,712:
Visitor class>>block: aBlock
^self new block: aBlock
</syntaxhighlight>
</lang>
 
'''Visitor subclass: InOrder'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
InOrder>>visit: aNode
aNode left accept: self.
block value: aNode.
aNode right accept: self
</syntaxhighlight>
</lang>
 
'''Visitor subclass: LevelOrder'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
LevelOrder>>visit: aNode
| queue |
Line 9,811 ⟶ 10,735:
add: aNode right;
yourself
</syntaxhighlight>
</lang>
 
'''Visitor subclass: PostOrder'''
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
PostOrder>>visit: aNode
aNode left accept: self.
aNode right accept: self.
block value: aNode
</syntaxhighlight>
</lang>
 
"Visitor subclass: PreOrder"
<langsyntaxhighlight lang="smalltalk">"Protocol: visiting"
PreOrder>>visit: aNode
block value: aNode.
aNode left accept: self.
aNode right accept: self
</syntaxhighlight>
</lang>
 
Execute code in a Workspace:
<langsyntaxhighlight lang="smalltalk">| tree |
tree := (Node data: 1)
left: ((Node data: 2)
Line 9,848 ⟶ 10,772:
tree traverse: LevelOrder do: [:node | Transcript print: node data; space].
Transcript cr.
</syntaxhighlight>
</lang>
 
Output in Transcript:
Line 9,857 ⟶ 10,781:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">class TreeNode<T> {
let value: T
let left: TreeNode?
Line 9,942 ⟶ 10,866:
print("level-order: ", terminator: "")
n.levelOrder(function: fn)
print()</langsyntaxhighlight>
 
{{out}}
Line 9,954 ⟶ 10,878:
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">oo::class create tree {
# Basic tree data structure stuff...
variable val l r
Line 10,003 ⟶ 10,927:
}
}
}</langsyntaxhighlight>
Note that in Tcl it is conventional to handle performing something “for each element” by evaluating a script in the caller's scope for each node after setting a caller-nominated variable to the value for that iteration. Doing this transparently while recursing requires the use of a varying ‘level’ parameter to <code>upvar</code> and <code>uplevel</code>, but makes for compact and clear code.
 
Demo code to satisfy the official challenge instance:
<langsyntaxhighlight lang="tcl"># Helpers to make construction and listing of a whole tree simpler
proc Tree nested {
lassign $nested v l r
Line 10,028 ⟶ 10,952:
puts "postorder: [Listify $t postorder]"
puts "level-order: [Listify $t levelorder]"
$t destroy</langsyntaxhighlight>
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 10,037 ⟶ 10,961:
=={{header|UNIX Shell}}==
Bash (also "sh" on most Unix systems) has arrays. We implement a node as an association between three arrays: left, right, and value.
<langsyntaxhighlight lang="bash">left=()
right=()
value=()
Line 10,120 ⟶ 11,044:
inorder 1
postorder 1
levelorder 1</langsyntaxhighlight>
The output:
<langsyntaxhighlight lang="bash">preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 10,137 ⟶ 11,061:
the result on standard output as a
list of lists of naturals.
<langsyntaxhighlight Ursalalang="ursala">tree =
 
1^:<
Line 10,150 ⟶ 11,074:
#cast %nLL
 
main = <.pre,in,post,lev> tree</langsyntaxhighlight>
output:
<pre>
Line 10,162 ⟶ 11,086:
=={{header|VBA}}==
TreeItem Class Module
<syntaxhighlight lang="vb">
<lang VB>
Public Value As Integer
Public LeftChild As TreeItem
Public RightChild As TreeItem
</syntaxhighlight>
</lang>
Module
<syntaxhighlight lang="vb">
<lang VB>
Dim tihead As TreeItem
 
Line 10,240 ⟶ 11,164:
Call LevelOrder(tihead)
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 10,248 ⟶ 11,172:
level-order: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
' 1
' / \
' / \
' / \
' 2 3
' / \ /
' 4 5 6
' / / \
' 7 8 9
'with no pointers available, the binary tree has to be saved in an array
' root at index 1
' parent index is i\2
' children indexes are i*2 and i*2+1
' a value of 0 denotes an empty branch
 
Sub print(s):
On Error Resume Next
WScript.stdout.Write(s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
 
 
Sub inorder(i)
If tree(i*2)<>0 Then inorder(i*2)
print tree(i)& vbtab
If tree(i*2+1)<>0 Then inorder(i*2+1)
End Sub
 
 
Sub preorder(i)
print tree(i)& vbtab
If tree(i*2)<>0 Then preorder(i*2)
If tree(i*2+1)<>0 Then preorder(i*2+1)
End Sub
Sub postorder(i)
If tree(i*2)<>0 Then postorder(i*2)
If tree(i*2+1)<>0 Then postorder(i*2+1)
print tree(i)& vbTab
End Sub
Sub levelorder(x)
Dim i
For i= 1 To UBound(tree)
If tree(i)<>0 Then print tree(i)& vbTab
Next
End sub
 
Dim tree
' 1 2 3 4 5 6 7 8 9 1011121314151617181920212223242526
' 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4
tree=Array(0,1,2,3,4,5,6,0,7,0,0,0,8,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
print vbCrLf & "Preorder" & vbcrlf
preorder(1)
print vbCrLf & "Inorder" & vbcrlf
inorder(1)
print vbCrLf & "Postorder" & vbcrlf
postorder(1)
print vbCrLf & "Levelorder" & vbcrlf
levelorder(1)
</syntaxhighlight>
{{out}}
<small>
<pre>
Preorder
1 2 4 7 5 3 6 8 9
Inorder
7 4 2 5 1 8 6 9 3
Postorder
7 4 5 2 8 9 6 3 1
Levelorder
1 2 3 4 5 6 7 8 9
</pre>
</small>
 
=={{header|Wren}}==
{{trans|Kotlin}}
The object-oriented version.
<langsyntaxhighlight ecmascriptlang="wren">class Node {
construct new(v) {
_v = v
Line 10,318 ⟶ 11,319:
nodes[1].exec(" inOrder:", Fn.new { |n| n.inOrder() })
nodes[1].exec(" postOrder:", Fn.new { |n| n.postOrder() })
nodes[1].exec("level-order:", Fn.new { |n| n.levelOrder() })</langsyntaxhighlight>
 
{{out}}
Line 10,326 ⟶ 11,327:
postOrder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">def \Node\ Left, Data, Right;
 
proc PreOrder(Node); \Traverse tree at Node in preorder
int Node;
[if Node # 0 then
[IntOut(0, Node(Data)); ChOut(0, ^ );
PreOrder(Node(Left));
PreOrder(Node(Right));
];
];
 
proc InOrder(Node); \Traverse tree at Node in inorder
int Node;
[if Node # 0 then
[InOrder(Node(Left));
IntOut(0, Node(Data)); ChOut(0, ^ );
InOrder(Node(Right));
];
];
 
proc PostOrder(Node); \Traverse tree at Node in postorder
int Node;
[if Node # 0 then
[PostOrder(Node(Left));
PostOrder(Node(Right));
IntOut(0, Node(Data)); ChOut(0, ^ );
];
];
 
proc LevelOrder(Node); \Traverse tree at Node in level-order
int Node;
def S=100*3; \size of queue (must be a multiple of 3 for wrap-around)
int Q(S), \queue (FIFO)
F, E; \fill and empty indexes
 
proc EnQ(Node); \Enqueue Node
int Node;
[Q(F):= Node(Left); F:= F+1;
Q(F):= Node(Data); F:= F+1;
Q(F):= Node(Right); F:= F+1;
if F >= S then F:= 0;
];
 
proc DeQ; \Dequeue Node
[Node(Left):= Q(E); E:= E+1;
Node(Data):= Q(E); E:= E+1;
Node(Right):= Q(E); E:= E+1;
if E >= S then E:= 0;
];
 
[F:= 0; E:= 0; \empty queue
EnQ(Node);
while E # F do
[DeQ;
IntOut(0, Node(Data)); ChOut(0, ^ );
if Node(Left) # 0 then
EnQ(Node(Left));
if Node(Right) # 0 then
EnQ(Node(Right));
];
];
 
int Tree;
[Tree:= [[ [[0,7,0],4,0], 2, [0,5,0]], 1, [ [[0,8,0], 6, [0,9,0]], 3, 0 ]];
Text(0, "preorder: "); PreOrder(Tree); CrLf(0);
Text(0, "inorder: "); InOrder(Tree); CrLf(0);
Text(0, "postorder: "); PostOrder(Tree); CrLf(0);
Text(0, "level-order: "); LevelOrder(Tree); CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Node{ var [mixin=Node]left,right; var v;
fcn init(val,[Node]l=Void,[Node]r=Void) { v,left,right=vm.arglist }
}
Line 10,359 ⟶ 11,438:
sink
}
}</langsyntaxhighlight>
It is easy to convert to lazy by replacing "sink.write" with "vm.yield" and wrapping the traversal with a Utils.Generator.
<langsyntaxhighlight lang="zkl">t:=BTree(Node(1,
Node(2,
Node(4,Node(7)),
Line 10,371 ⟶ 11,450:
t.inOrder() .apply("v").println(" inorder");
t.postOrder() .apply("v").println(" postorder");
t.levelOrder().apply("v").println(" level-order");</langsyntaxhighlight>
The "apply("v")" extracts the contents of var v from each node.
{{out}}
1,480

edits