Tree traversal: Difference between revisions

lang -> syntaxhighlight
m (→‎Haskell: Reduced `treeLeaves` to a foldTree expression)
(lang -> syntaxhighlight)
Line 34:
{{trans|Python: Class based}}
 
<langsyntaxhighlight lang=11l>T Node
Int data
Node? left
Line 105:
print(‘levelorder: ’, end' ‘’)
tree.levelorder(printwithspace)
print()</langsyntaxhighlight>
 
{{out}}
Line 117:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deftree64.s */
Line 505:
/* 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:
(defun flatten-level (tree)
(let ((levels (flatten-level-r1 tree 0 nil)))
(flatten-level-r2 levels (len levels))))</langsyntaxhighlight>
 
=={{header|Action!}}==
Line 560:
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 lang=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:
 
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:
 
=={{header|Ada}}==
<langsyntaxhighlight lang=Ada>with Ada.Text_Io; use Ada.Text_Io;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
Line 928:
New_Line;
Destroy_Tree(N);
end Tree_traversal;</langsyntaxhighlight>
 
=={{header|Agda}}==
<langsyntaxhighlight lang=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:
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:
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:
 
{{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:
 
destroy tree(node)
)</langsyntaxhighlight>
Output:
<pre>
Line 1,152:
 
Written in Dyalog APL with dfns.
<langsyntaxhighlight lang=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:
and empty childL or childR mean and absence of the corresponding child node.
 
<langsyntaxhighlight lang=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:
=={{header|AppleScript}}==
{{Trans|JavaScript}}(ES6)
<langsyntaxhighlight lang=AppleScript>on run
-- Sample tree of integers
set tree to node(1, ¬
Line 1,212:
-- '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:
-- inorder :: a -> [[a]] -> [a]
on inorder(x, xs)
if {} ? xs then
item 1 of xs & x & concat(rest of xs)
else
Line 1,272:
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:
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:
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:
-- 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:
{{root of node} & h} & foldr(go, t, nest of node)
end |λ?|
end script
|λ?|(tree, {}) of go
end levels
 
Line 1,390:
else
script
property |λ?| : f
end script
end if
Line 1,401:
-- 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:
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:
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:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 1,975:
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 2,022:
 
=={{header|ATS}}==
<langsyntaxhighlight lang=ATS>#include
"share/atspre_staload.hats"
//
Line 2,119:
println! ("postorder:\t", postorder(t0));
println! ("level-order:\t", levelorder(t0));
end (* end of [main0] *)</langsyntaxhighlight>
 
{{out}}
Line 2,129:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
<langsyntaxhighlight lang=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:
t .= i%Lev%, Lev++
Return t
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang=awk>
function preorder(tree, node, res, child) {
if (node == "")
Line 2,274:
delete result
}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang=bracmat>(
( tree
= 1
Line 2,317:
& out$("level-order:" levelorder$(!tree.))
&
)</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#include <stdlib.h>
#include <stdio.h>
 
Line 2,465:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Linq;
Line 2,539:
Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal()));
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Line 2,546:
{{libheader|Boost|1.39.0}}
 
<langsyntaxhighlight lang=cpp>#include <boost/scoped_ptr.hpp>
#include <iostream>
#include <queue>
Line 2,639:
 
return 0;
}</langsyntaxhighlight>
 
===Array version===
<langsyntaxhighlight lang=cpp>#include <iostream>
 
using namespace std;
Line 2,710:
level_order(t);
cout << endl;
}</langsyntaxhighlight>
 
===Modern C++===
{{works with|C++14}}
<langsyntaxhighlight lang=cpp>#include <iostream>
#include <memory>
#include <queue>
Line 2,808:
n.level_order(print);
std::cout << '\n';
}</langsyntaxhighlight>
 
{{out}}
Line 2,819:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang=ceylon>import ceylon.collection {
ArrayList
}
Line 2,915:
levelOrder(tree);
print("");
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=clojure>(defn walk [node f order]
(when node
(doseq [o order]
Line 2,961:
(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:
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:
 
=={{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:
test_walk "postorder"
test_walk "levelorder"
</syntaxhighlight>
</lang>
output
<syntaxhighlight>
<lang>
> coffee tree_traversal.coffee
preorder 1 2 4 7 5 3 6 8 9
Line 3,120:
postorder 7 4 5 2 8 9 6 3 1
levelorder 1 2 3 4 5 6 7 8 9
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang=lisp>(defun preorder (node f)
(when node
(funcall f (first node))
Line 3,161:
(funcall traversal-function *tree* (lambda (value) (format t " ~A" value))))
 
(map nil #'show '(preorder inorder postorder level-order))</langsyntaxhighlight>
 
Output:
Line 3,172:
=={{header|Coq}}==
 
<langsyntaxhighlight lang=coq>Require Import Utf8.
Require Import List.
 
Line 3,181:
 
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:
match c with
| nil => n :: nil
| l :: r => inorder l ++ n :: flat_map inorder r
end.
 
Line 3,212:
| 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:
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:
puts
 
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,320:
=={{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:
tree.levelOrder;
writeln;
}</langsyntaxhighlight>
{{out}}
<pre> preOrder: 1 2 4 7 5 3 6 8 9
Line 3,406:
{{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:
writeln(postOrder(tree));
writeln(levelOrder(tree));
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 4, 7, 5, 3, 6, 8, 9]
Line 3,458:
===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:
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]
Line 3,530:
=={{header|E}}==
 
<langsyntaxhighlight lang=e>def btree := [1, [2, [4, [7, null, null],
null],
[5, null, null]],
Line 3,576:
print("level-order:")
levelOrder(btree, fn v { print(" ", v) })
println()</langsyntaxhighlight>
 
=={{header|Eiffel}}==
Line 3,582:
 
Void-Safety has been disabled for simplicity of the code.
<langsyntaxhighlight lang=eiffel >note
description : "Application for tree traversal demonstration"
output : "[
Line 3,632:
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:
 
end
-- class NODE</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang=elena>import extensions;
import extensions'routines;
import system'collections;
Line 3,883:
console.printLine("Postorder :", tree.Postorder);
console.printLine("LevelOrder:", tree.LevelOrder)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,894:
=={{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].
<langsyntaxhighlight lang=Elisa>
component BinaryTreeTraversals (Tree, Element);
type Tree;
Line 3,931:
];
end component BinaryTreeTraversals;
</syntaxhighlight>
</lang>
Tests
<langsyntaxhighlight lang=Elisa>
use BinaryTreeTraversals (Tree, integer);
 
Line 3,953:
{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:
end
 
Tree_Traversal.main</langsyntaxhighlight>
 
{{out}}
Line 4,023:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=erlang>-module(tree_traversal).
-export([main/0]).
-export([preorder/2, inorder/2, postorder/2, levelorder/2]).
Line 4,064:
inorder(F, Tree), ?NEWLINE,
postorder(F, Tree), ?NEWLINE,
levelorder(F, Tree), ?NEWLINE.</langsyntaxhighlight>
 
Output:
Line 4,074:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang=euphoria>constant VALUE = 1, LEFT = 2, RIGHT = 3
 
constant tree = {1,
Line 4,140:
puts(1,"level-order: ")
level_order(tree)
puts(1,'\n')</langsyntaxhighlight>
 
Output:
Line 4,149:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>open System
open System.IO
 
Line 4,223:
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:
[ "levelorder: " write levelorder nl ]
[ "levelorder2: " write levelorder2 nl ]
} 2cleave ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
<langsyntaxhighlight lang=fantom>
class Tree
{
Line 4,370:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 4,381:
 
=={{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:
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:
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 lang=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:
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 lang=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===
<langsyntaxhighlight lang=Fortran>
MODULE ARAUCARIA !Cunning crosswords, also.
INTEGER ENUFF !To suit the set example.
Line 4,668:
CALL JANE("LEVEL") !Alternatively...
END !So much for that.
</syntaxhighlight>
</lang>
===Output===
Alternately GORILLA-style, and JANE-style:
Line 4,687:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang=freebasic>
#define NULL 0
 
Line 4,760:
Wend
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,772:
=={{header|FunL}}==
{{trans|Haskell}}
<langsyntaxhighlight lang=funl>data Tree = Empty | Node( value, left, right )
 
def
Line 4,807:
println( inorder(tree) )
println( postorder(tree) )
println( levelorder(tree) )</langsyntaxhighlight>
 
{{out}}
Line 4,818:
</pre>
 
=={{header|FōrmulæFormulæ}}==
 
FōrmulæFormulæ 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.
 
Programs in FōrmulæFormulæ 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.
 
In '''[https://formulae.org/?example=Tree_traversal this]''' page you can see the program(s) related to this task and their results.
Line 4,828:
=={{header|GFA Basic}}==
 
<syntaxhighlight>
<lang>
maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
Line 4,945:
WEND
RETURN
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
Line 4,951:
{{trans|C}}
This is like many examples on this page.
<langsyntaxhighlight lang=go>package main
 
import "fmt"
Line 5,036:
func visitor(value int) {
fmt.Print(value, " ")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,046:
===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:
}
}
}</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:
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:
} 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:
'6' { '8' {}; '9' {} }
}
}</langsyntaxhighlight>
 
Test case #2 (tests single right child)
<langsyntaxhighlight lang=groovy>// 1
// / \
// 2 3
Line 5,204:
'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:
}
test(tree1)
test(tree2)</langsyntaxhighlight>
 
Output:
Line 5,242:
=={{header|Haskell}}==
===Left Right nodes===
<langsyntaxhighlight lang=haskell>---------------------- TREE TRAVERSAL --------------------
 
data Tree a
Line 5,311:
([preorder, inorder, postorder, levelorder] <*> [tree])
where
justifyLeft n c s = take n (s <> replicate n c)</langsyntaxhighlight>
{{Out}}
<pre> 1
Line 5,452:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang=Icon>procedure main()
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
showTree(bTree, preorder|inorder|postorder|levelorder)
Line 5,483:
}
}
end</langsyntaxhighlight>
 
Output:
Line 5,495:
 
=={{header|Isabelle}}==
<langsyntaxhighlight lang=Isabelle>theory Tree
imports Main
begin
Line 5,502:
 
definition example :: "int tree" where
"example =
Node
(Node
Line 5,524:
)"
 
fun preorder :: "'a tree ? 'a list" where
"preorder Leaf = []"
| "preorder (Node l a r) = a # preorder l @ preorder r"
Line 5,530:
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,536:
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,556:
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,566:
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 lang=J>preorder=: ]S:0
postorder=: ([:; postorder&.>@}.) , >@{.
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
inorder=: ([:; inorder&.>@(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}.</langsyntaxhighlight>
 
Required example:
 
<langsyntaxhighlight lang=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 lang=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 lang=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 lang=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 lang=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 lang=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,621:
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 lang=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,627:
Next, let's define a few utilities:
 
<langsyntaxhighlight lang=J>depth=: +/@((~: , (~: i.@#@{.)~) {:@,)@({~^:a:)
 
reorder=:4 :0
Line 5,639:
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,651:
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 lang=J>dataorder=: /:@data reorder ]
levelorder=: /:@depth@parent reorder ]
 
Line 5,703:
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,709:
Example use:
 
<langsyntaxhighlight lang=J> levelorder dataorder example
1 2 3 4 5 6 7 8 9
0 0 0 1 1 2 3 5 5
Line 5,720:
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,732:
 
{{works with|Java|1.5+}}
<langsyntaxhighlight lang=java5>import java.util.*;
 
public class TreeTraversal {
Line 5,818:
}
}</langsyntaxhighlight>
Output:
<pre>1 2 4 7 5 3 6 8 9
Line 5,833:
 
{{works with|Java|1.8+}}
<langsyntaxhighlight lang=java5>import java.util.function.Consumer;
import java.util.Queue;
import java.util.LinkedList;
Line 5,958:
System.out.println();
}
}</langsyntaxhighlight>
 
Output:
Line 5,970:
====Iteration====
inspired by [[#Ruby|Ruby]]
<langsyntaxhighlight lang=javascript>function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
Line 6,009:
print("*** inorder ***"); tree.inorder(print);
print("*** postorder ***"); tree.postorder(print);
print("*** levelorder ***"); tree.levelorder(print);</langsyntaxhighlight>
 
====Functional composition====
Line 6,015:
(for binary trees consisting of nested lists)
 
<langsyntaxhighlight lang=javascript>(function () {
 
function preorder(n) {
Line 6,103:
return wikiTable(lstTest, true) + '\n\n' + JSON.stringify(lstTest);
 
})();</langsyntaxhighlight>
 
Output:
Line 6,120:
|}
 
<langsyntaxhighlight lang=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,132:
 
 
<langsyntaxhighlight lang=JavaScript>(function () {
'use strict';
 
Line 6,252:
}, {});
 
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang=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,263:
{{Trans|Haskell}}
{{Trans|Python}}
<langsyntaxhighlight lang=JavaScript>(() => {
"use strict";
 
Line 6,309:
// task: 'Visualize a tree'
console.log([
" + 4 - 7",
" + 2 ¦",
" ¦ + 5",
" 1 ¦",
" ¦ + 8",
" + 3 - 6 ¦",
" + 9"
].join("\n"));
 
Line 6,390:
// 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,408:
 
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,434:
 
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,452:
;
 
task</langsyntaxhighlight>
{{Out}}
$ jq -n -c -r -f Tree_traversal.jq
Line 6,461:
 
=={{header|Julia}}==
<langsyntaxhighlight lang=Julia>tree = Any[1, Any[2, Any[4, Any[7, Any[],
Any[]],
Any[]],
Line 6,487:
t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t)
end
</syntaxhighlight>
</lang>
 
{{Out}}
Line 6,502:
=={{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,568:
exec(" postOrder: ", nodes[1], ::postOrder)
exec("level-order: ", nodes[1], ::levelOrder)
}</langsyntaxhighlight>
 
{{Out}}
Line 6,579:
 
===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,620:
exec("level-order:", Node::levelOrder)
}
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
Line 6,633:
- {A.get index array} gets the value of array at index
</pre>
<langsyntaxhighlight lang=scheme>
{def walk
 
Line 6,668:
{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,698:
on getRight (me)
return me._right
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang=lingo>-- parent script "BinaryTreeTraversal"
 
on inOrder (me, node, l)
Line 6,750:
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,772:
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,783:
 
=={{header|Logo}}==
<langsyntaxhighlight lang=logo>; nodes are [data left right], use "first" to get data
 
to node.left :node
Line 6,839:
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,923:
 
:- 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,932:
Level-order: 1 2 3 4 5 6 7 8 9
yes
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang=Lua>-- Utility
local function append(t1, t2)
for _, v in ipairs(t2) do
Line 6,980:
print("inorder: " .. table.concat(tree:order({2, 1, 3}), " "))
print("postorder: " .. table.concat(tree:order({2, 3, 1}), " "))
print("level-order: " .. table.concat(tree:levelorder(), " "))</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 6,986:
A tuple is an "auto array" in M2000 Interpreter. (,) is the zero length array.
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module CheckIt {
Null=(,)
Line 7,046:
}
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.
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,135:
}
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)
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,227:
}
OOP
</syntaxhighlight>
</lang>
 
Using Event object as visitor
 
<langsyntaxhighlight lang=M2000 Interpreter>
Module OOP {
\\ Class is a global function (until this module end)
Line 7,322:
}
OOP
</syntaxhighlight>
</lang>
 
{{out}}
Line 7,333:
 
=={{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,341:
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,355:
 
=={{header|Mercury}}==
<langsyntaxhighlight lang=mercury>:- module tree_traversal.
:- interface.
 
Line 7,447:
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,455:
 
=={{header|Nim}}==
<langsyntaxhighlight lang=nim>import deques
 
type
Line 7,499:
echo inorder tree
echo postorder tree
echo levelorder tree</langsyntaxhighlight>
 
{{out}}
Line 7,508:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang=objeck>
use??use Collection;
 
class Test {
Line 7,621:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 7,632:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>type 'a tree = Empty
| Node of 'a * 'a tree * 'a tree
 
Line 7,681:
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,690:
=={{header|Oforth}}==
 
<langsyntaxhighlight lang=Oforth>Object Class new: Tree(v, l, r)
 
Tree method: initialize(v, l, r) v := v l := l r := r ;
Line 7,720:
n l dup ifNotNull: [ c send ] drop
n r dup ifNotNull: [ c send ] drop
] ;</langsyntaxhighlight>
 
{{out}}
Line 7,743:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang=ooRexx>
one = .Node~new(1);
two = .Node~new(2);
Line 7,827:
nodequeue~queue(next~right)
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 7,837:
 
=={{header|Oz}}==
<langsyntaxhighlight lang=oz>declare
Tree = n(1
n(2
Line 7,894:
{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,933:
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,945:
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 lang=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,992:
<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,003:
 
=={{header|PHP}}==
<langsyntaxhighlight lang=PHP>class Node {
private $left;
private $right;
Line 8,104:
$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,112:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de preorder (Node Fun)
(when Node
(Fun (car Node))
Line 8,145:
(prin (align -13 (pack Order ":")))
(Order *Tree printsp)
(prinl) )</langsyntaxhighlight>
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,154:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight lang=Prolog>tree :-
Tree= [1,
[2,
Line 8,210:
 
append_dl(X-Y, Y-Z, X-Z).
</syntaxhighlight>
</lang>
Output :
<pre>?- tree.
Line 8,222:
=={{header|PureBasic}}==
{{works with|PureBasic|4.5+}}
<langsyntaxhighlight lang=PureBasic>Structure node
value.i
*left.node
Line 8,356:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,367:
===Python: Procedural===
 
<langsyntaxhighlight lang=python>from collections import namedtuple
Node = namedtuple('Node', 'data, left, right')
Line 8,438:
print(f"{traversal.__name__:>{w}}:", end=' ')
traversal(tree)
print()</langsyntaxhighlight>
 
'''Sample output:'''
Line 8,454:
 
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,514:
stdout.write('\nlevelorder: ')
tree.levelorder(printwithspace)
stdout.write('\n')</langsyntaxhighlight>
 
{{out}}
Line 8,531:
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,741:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Tree traversals - accumulating and folding:
Line 8,758:
 
=={{header|Qi}}==
<syntaxhighlight lang=qi>
<lang qi>
(set *tree* [1 [2 [4 [7]]
[5]]
Line 8,803:
(inorder (value *tree*))
(levelorder (value *tree*))
</syntaxhighlight>
</lang>
 
Output:
Line 8,815:
Requires the words at [[Queue/Definition#Quackery]] for <code>level-order</code>.
 
<langsyntaxhighlight lang=Quackery> [ this ] is nil ( --> [ )
 
[ ' [ 1
Line 8,861:
tree in-order cr
tree post-order cr
tree level-order cr</langsyntaxhighlight>
 
{{out}}
Line 8,872:
=={{header|Racket}}==
 
<langsyntaxhighlight lang=racket>
#lang racket
 
Line 8,895:
(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,910:
=={{header|Raku}}==
(formerly Perl 6)
<langsyntaxhighlight lang=perl6>class TreeNode {
has TreeNode $.parent;
has TreeNode $.left;
Line 8,967:
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,975:
 
=={{header|REBOL}}==
<langsyntaxhighlight lang=REBOL>
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
; "compacted" version
Line 9,022:
]
prin "level-order: " level-order tree
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 9,032:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>
/* REXX ***************************************************************
* Tree traversal
Line 9,350:
Say ''
End
Return</langsyntaxhighlight>
{{out}}
<pre> 1
Line 9,366:
 
=={{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,405:
root.send(mthd) {|node| print "#{node.value} "}
puts
end</langsyntaxhighlight>
 
{{out}}
Line 9,416:
=={{header|Rust}}==
This solution uses iteration (rather than recursion) for all traversal types.
<langsyntaxhighlight lang=Rust>
#![feature(box_syntax, box_patterns)]
 
Line 9,592:
}
}
</syntaxhighlight>
</lang>
Output is same as Ruby et al.
 
=={{header|Scala}}==
{{works with|Scala|2.11.x}}
<langsyntaxhighlight lang=Scala>case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) {
 
def preorder(f: IntNode => Unit) {
Line 9,651:
println(s)
}
}</langsyntaxhighlight>
 
Output:<pre>
Line 9,661:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang=scheme>(define (preorder tree)
(if (null? tree)
'()
Line 9,726:
())))
 
(demonstration the-task-tree)</langsyntaxhighlight>
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 9,734:
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang=sequenceL>
main(args(2)) :=
"preorder: " ++ toString(preOrder(testTree)) ++
Line 9,777:
)
);
</syntaxhighlight>
</lang>
{{out}}
Output:
Line 9,789:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang=ruby>func preorder(t) {
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
}
Line 9,816:
say "in: #{inorder(x)}";
say "post: #{postorder(x)}";
say "depth: #{depth(x)}";</langsyntaxhighlight>
{{out}}
<pre>
Line 9,835:
 
'''Object subclass: EmptyNode'''
<langsyntaxhighlight lang=smalltalk>"Protocol: visiting"
EmptyNode>>accept: aVisitor
 
Line 9,844:
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,882:
Node class>>data: anObject
^self new data: anObject
</syntaxhighlight>
</lang>
 
'''Object subclass: Visitor'''
<langsyntaxhighlight lang=smalltalk>"Protocol: visiting"
visit: aNode
self subclassResponsibility
Line 9,902:
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,925:
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,962:
tree traverse: LevelOrder do: [:node | Transcript print: node data; space].
Transcript cr.
</syntaxhighlight>
</lang>
 
Output in Transcript:
Line 9,971:
 
=={{header|Swift}}==
<langsyntaxhighlight lang=swift>class TreeNode<T> {
let value: T
let left: TreeNode?
Line 10,056:
print("level-order: ", terminator: "")
n.levelOrder(function: fn)
print()</langsyntaxhighlight>
 
{{out}}
Line 10,068:
=={{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,117:
}
}
}</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,142:
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,151:
=={{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,234:
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,251:
the result on standard output as a
list of lists of naturals.
<langsyntaxhighlight lang=Ursala>tree =
 
1^:<
Line 10,264:
#cast %nLL
 
main = <.pre,in,post,lev> tree</langsyntaxhighlight>
output:
<pre>
Line 10,276:
=={{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,354:
Call LevelOrder(tihead)
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 10,366:
{{trans|Kotlin}}
The object-oriented version.
<langsyntaxhighlight lang=ecmascript>class Node {
construct new(v) {
_v = v
Line 10,432:
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,443:
 
=={{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,473:
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,485:
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}}
6,962

edits