Tree traversal: Difference between revisions
lang -> syntaxhighlight
m (→Haskell: Reduced `treeLeaves` to a foldTree expression) |
(lang -> syntaxhighlight) |
||
Line 34:
{{trans|Python: Class based}}
<
Int data
Node? left
Line 105:
print(‘levelorder: ’, end' ‘’)
tree.levelorder(printwithspace)
print()</
{{out}}
Line 117:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* 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>
=={{header|ACL2}}==
<
(if (endp tree)
nil
Line 554:
(defun flatten-level (tree)
(let ((levels (flatten-level-r1 tree 0 nil)))
(flatten-level-r2 levels (len levels))))</
=={{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}}
<
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</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Tree_traversal.png Screenshot from Atari 8-bit computer]
Line 821:
=={{header|Ada}}==
<
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
Line 928:
New_Line;
Destroy_Tree(N);
end Tree_traversal;</
=={{header|Agda}}==
<
open import Data.Nat using (
open import Level using (Level)
open import Relation.Binary.PropositionalEquality using (
data Tree {a} (A : Set a) : Set a where
leaf : Tree A
node : A
variable
Line 944:
A : Set a
preorder : Tree A
preorder tr = go tr []
where
go : Tree A
go leaf ys = ys
go (node x ls rs) ys = x
inorder : Tree A
inorder tr = go tr []
where
go : Tree A
go leaf ys = ys
go (node x ls rs) ys = go ls (x
postorder : Tree A
postorder tr = go tr []
where
go : Tree A
go leaf ys = ys
go (node x ls rs) ys = go ls (go rs (x
level-order : Tree A
level-order tr = concat (go tr [])
where
go : Tree A
go leaf qs = qs
go (node x ls rs) [] = (x
go (node x ls rs) (q
example-tree : Tree
example-tree =
node 1
Line 995:
leaf)
_ : preorder example-tree
_ = refl
_ : inorder example-tree
_ = refl
_ : postorder example-tree
_ = refl
_ : level-order example-tree
_ = refl</
=={{header|ALGOL 68}}==
Line 1,017:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<
PROC value repr = (VALUE value)STRING: whole(value, 0);
Line 1,140:
destroy tree(node)
)</
Output:
<pre>
Line 1,152:
Written in Dyalog APL with dfns.
<
inorder
postorder? {l r?? ?? ? ? ? ???(?r)???(×?r)?(?l)???(×?l)??}
lvlorder
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.
<
visit?{?,(×??)???}
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>
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>
Line 1,198:
=={{header|AppleScript}}==
{{Trans|JavaScript}}(ES6)
<
-- Sample tree of integers
set tree to node(1, ¬
Line 1,212:
-- 'Visualize a Tree':
set strTree to unlines({¬
"
"
"
" 1
"
"
"
script tabulate
on |
justifyRight(14, space, s & ": ") & unwords(xs)
end |
end script
Line 1,249:
-- inorder :: a -> [[a]] -> [a]
on inorder(x, xs)
if {}
item 1 of xs & x & concat(rest of xs)
else
Line 1,272:
on foldTree(f)
script
on |
script go
property g : |
on |
g(root of oNode, |
of map(go))
end |
end script
|
end |
end script
end foldTree
Line 1,306:
tell mReturn(contents of f)
repeat with x in xs
set end of lst to |
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 |
end repeat
return v
Line 1,369:
-- values of each level of the tree.
script go
on |
if {}
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
|
end levels
Line 1,390:
else
script
property |
end script
end if
Line 1,401:
-- to each element of xs.
script
on |
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |
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 |
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 |
end repeat
return lst
end tell
end zipWith</
{{Out}}
<pre>
1
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}}
<
/* ARM assembly Raspberry PI */
Line 1,975:
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
{{output}}
<pre>
Line 2,022:
=={{header|ATS}}==
<
"share/atspre_staload.hats"
//
Line 2,119:
println! ("postorder:\t", postorder(t0));
println! ("level-order:\t", levelorder(t0));
end (* end of [main0] *)</
{{out}}
Line 2,129:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
<
AddNode(Tree,2,4,5,2)
AddNode(Tree,3,6,0,3)
Line 2,181:
t .= i%Lev%, Lev++
Return t
}</
=={{header|AWK}}==
<
function preorder(tree, node, res, child) {
if (node == "")
Line 2,274:
delete result
}
</syntaxhighlight>
=={{header|Bracmat}}==
<
( tree
= 1
Line 2,317:
& out$("level-order:" levelorder$(!tree.))
&
)</
=={{header|C}}==
<
#include <stdio.h>
Line 2,465:
return 0;
}</
=={{header|C sharp}}==
<
using System.Collections.Generic;
using System.Linq;
Line 2,539:
Console.WriteLine("{0}:\t{1}", traversal.Method.Name, string.Join(" ", traversal()));
}
}</
=={{header|C++}}==
Line 2,546:
{{libheader|Boost|1.39.0}}
<
#include <iostream>
#include <queue>
Line 2,639:
return 0;
}</
===Array version===
<
using namespace std;
Line 2,710:
level_order(t);
cout << endl;
}</
===Modern C++===
{{works with|C++14}}
<
#include <memory>
#include <queue>
Line 2,808:
n.level_order(print);
std::cout << '\n';
}</
{{out}}
Line 2,819:
=={{header|Ceylon}}==
<
ArrayList
}
Line 2,915:
levelOrder(tree);
print("");
}</
=={{header|Clojure}}==
<
(when node
(doseq [o order]
Line 2,961:
(print (format "%-12s" (str f ":")))
((resolve f) tree pr-node)
(println)))</
=={{header|CLU}}==
<
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</
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 3,065:
=={{header|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>
output
<syntaxhighlight>
> 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>
=={{header|Common Lisp}}==
<
(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))</
Output:
Line 3,172:
=={{header|Coq}}==
<
Require Import List.
Line 3,181:
Fixpoint height (t: tree) : nat :=
1 + fold_left (
Example leaf n : tree := {| value := n ; children := nil |}.
Line 3,199:
match c with
| nil => n :: nil
|
end.
Line 3,212:
| O => nil
| S fuel' =>
let '(p, f) := fold_right (
p ++ levelorder_forest fuel' f
end.
Line 3,223:
Compute postorder t9.
Compute levelorder t9.
</syntaxhighlight>
=={{header|Crystal}}==
{{trans|C++}}
<
class Node(T)
property left : Nil | Node(T)
Line 3,309:
puts
</syntaxhighlight>
Output:
<pre>
Line 3,320:
=={{header|D}}==
This code is long because it's very generic.
<
const final class Node(T) {
Line 3,396:
tree.levelOrder;
writeln;
}</
{{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.
<
T v;
Node* l, r;
Line 3,449:
writeln(postOrder(tree));
writeln(levelOrder(tree));
}</
{{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.
<
const struct Tree(T) {
Line 3,522:
tree.inOrder.map!(t => t.value).writeln;
tree.postOrder.map!(t => t.value).writeln;
}</
{{out}}
<pre>[1, 2, 4, 7, 5, 3, 6, 8, 9]
Line 3,530:
=={{header|E}}==
<
null],
[5, null, null]],
Line 3,576:
print("level-order:")
levelOrder(btree, fn v { print(" ", v) })
println()</
=={{header|Eiffel}}==
Line 3,582:
Void-Safety has been disabled for simplicity of the code.
<
description : "Application for tree traversal demonstration"
output : "[
Line 3,632:
end
end -- class APPLICATION</
<
description : "A simple node for a binary tree"
libraries : "Relies on LINKED_LIST from EiffelBase"
Line 3,759:
end
-- class NODE</
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions'routines;
import system'collections;
Line 3,883:
console.printLine("Postorder :", tree.Postorder);
console.printLine("LevelOrder:", tree.LevelOrder)
}</
{{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].
<
component BinaryTreeTraversals (Tree, Element);
type Tree;
Line 3,931:
];
end component BinaryTreeTraversals;
</syntaxhighlight>
Tests
<
use BinaryTreeTraversals (Tree, integer);
Line 3,953:
{Item(Level_order(BT))}?
{ 1, 2, 3, 4, 5, 6, 7, 8, 9}
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
defp tnode, do: {}
defp tnode(v), do: {:node, v, {}, {}}
Line 4,012:
end
Tree_Traversal.main</
{{out}}
Line 4,023:
=={{header|Erlang}}==
<
-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.</
Output:
Line 4,074:
=={{header|Euphoria}}==
<
constant tree = {1,
Line 4,140:
puts(1,"level-order: ")
level_order(tree)
puts(1,'\n')</
Output:
Line 4,149:
=={{header|F_Sharp|F#}}==
<
open System.IO
Line 4,223:
printf "\nlevel-order: "
levelorder tree |> Seq.iter show
0</
=={{header|Factor}}==
<
math.parser ;
IN: rosetta.tree-traversal
Line 4,297:
[ "levelorder: " write levelorder nl ]
[ "levelorder2: " write levelorder2 nl ]
} 2cleave ;</
=={{header|Fantom}}==
<
class Tree
{
Line 4,370:
}
}
</syntaxhighlight>
Output:
Line 4,381:
=={{header|Forth}}==
<
: 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</
=={{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 <
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)</
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 <
DO GASP = 1,MAXLEVEL
CALL TARZAN(1,HOW)
END DO</
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===
<
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>
===Output===
Alternately GORILLA-style, and JANE-style:
Line 4,687:
=={{header|FreeBASIC}}==
<
#define NULL 0
Line 4,760:
Wend
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 4,772:
=={{header|FunL}}==
{{trans|Haskell}}
<
def
Line 4,807:
println( inorder(tree) )
println( postorder(tree) )
println( levelorder(tree) )</
{{out}}
Line 4,818:
</pre>
=={{header|
Programs in
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>
maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
Line 4,945:
WEND
RETURN
</syntaxhighlight>
=={{header|Go}}==
Line 4,951:
{{trans|C}}
This is like many examples on this page.
<
import "fmt"
Line 5,036:
func visitor(value int) {
fmt.Print(value, " ")
}</
{{out}}
<pre>
Line 5,046:
===Flat slice===
Alternative representation. Like Wikipedia [http://en.wikipedia.org/wiki/Binary_tree#Arrays Binary tree#Arrays]
<
import "fmt"
Line 5,116:
}
}
}</
=={{header|Groovy}}==
Uses Groovy '''Node''' and '''NodeBuilder''' classes
<
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
Line 5,154:
node
}
}</
Verify that '''BinaryNodeBuilder''' will not allow a node to have more than 2 children
<
new BinaryNodeBuilder().'1' {
a {}
Line 5,166:
} catch (org.codehaus.groovy.transform.powerassert.PowerAssertionError e) {
println 'limited to binary tree\r\n'
}</
Test case #1 (from the task definition)
<
// / \
// 2 3
Line 5,185:
'6' { '8' {}; '9' {} }
}
}</
Test case #2 (tests single right child)
<
// / \
// 2 3
Line 5,204:
'6' { '8' {}; '9' {} }
}
}</
Run tests:
<
println "preorder: ${preorder(tree).collect{it.name()}}"
println "preorder: ${tree.depthFirst().collect{it.name()}}"
Line 5,221:
}
test(tree1)
test(tree2)</
Output:
Line 5,242:
=={{header|Haskell}}==
===Left Right nodes===
<
data Tree a
Line 5,311:
([preorder, inorder, postorder, levelorder] <*> [tree])
where
justifyLeft n c s = take n (s <> replicate n c)</
{{Out}}
<pre> 1
Line 5,452:
=={{header|Icon}} and {{header|Unicon}}==
<
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
showTree(bTree, preorder|inorder|postorder|levelorder)
Line 5,483:
}
}
end</
Output:
Line 5,495:
=={{header|Isabelle}}==
<
imports Main
begin
Line 5,502:
definition example :: "int tree" where
"example
Node
(Node
Line 5,524:
)"
fun preorder :: "'a tree
"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
"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
"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
"tree_size Leaf = 1"
| "tree_size (Node l _ r) = 1 + tree_size l + tree_size r"
function (sequential) bfs :: "'a tree list
"bfs [] = []"
| "bfs (Leaf#q) = bfs q"
Line 5,566:
by pat_completeness auto
termination bfs
by(relation "measure (
fun levelorder :: "'a tree
"levelorder t = bfs [t]"
lemma "levelorder example = [1, 2, 3, 4, 5, 6, 7, 8, 9]" by code_simp
end</
=={{header|J}}==
<
postorder=: ([:; postorder&.>@}.) , >@{.
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
inorder=: ([:; inorder&.>@(''"_`(1&{)@.(1<#))) , >@{. , [:; inorder&.>@}.@}.</
Required example:
<
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</
This tree is organized in a pre-order fashion
<
1 2 4 7 5 3 6 8 9</
post-order is not that much different from pre-order, except that the children must extracted before the parent.
<
7 4 5 2 8 9 6 3 1</
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
<
7 4 2 5 1 8 6 9 3</
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.
<
1 2 3 4 5 6 7 8 9</
For J novices, here's the tree instance with a few redundant parenthesis:
<
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:
<
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:
<
reorder=:4 :0
Line 5,639:
parent=:3 :'parent[''data parent''=. y'
childinds=: [: <:@(2&{.@-.&> #\) (</. #\)`(]~.)`(a:"0)}~</
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):
<
levelorder=: /:@depth@parent reorder ]
Line 5,703:
todo=. todo,|.ch end. end.
r
)</
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:
<
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</
(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+}}
<
public class TreeTraversal {
Line 5,818:
}
}</
Output:
<pre>1 2 4 7 5 3 6 8 9
Line 5,833:
{{works with|Java|1.8+}}
<
import java.util.Queue;
import java.util.LinkedList;
Line 5,958:
System.out.println();
}
}</
Output:
Line 5,970:
====Iteration====
inspired by [[#Ruby|Ruby]]
<
this.value = value;
this.left = left;
Line 6,009:
print("*** inorder ***"); tree.inorder(print);
print("*** postorder ***"); tree.postorder(print);
print("*** levelorder ***"); tree.levelorder(print);</
====Functional composition====
Line 6,015:
(for binary trees consisting of nested lists)
<
function preorder(n) {
Line 6,103:
return wikiTable(lstTest, true) + '\n\n' + JSON.stringify(lstTest);
})();</
Output:
Line 6,120:
|}
<
["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]]]</
Line 6,132:
<
'use strict';
Line 6,252:
}, {});
})();</
{{Out}}
<
"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]}</
===ES6===
Line 6,263:
{{Trans|Haskell}}
{{Trans|Python}}
<
"use strict";
Line 6,309:
// task: 'Visualize a tree'
console.log([
"
"
"
" 1
"
"
"
].join("\n"));
Line 6,390:
// MAIN ---
return main();
})();</
{{Out}}
<pre>
1
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.
<
if length == 0 then empty
else .[0], (.[1]|preorder), (.[2]|preorder)
Line 6,434:
def levelorder: [.] | recurse( tails ) | heads;
</syntaxhighlight>
'''The task''':
<
# [node, left, right]
def atree: [1, [2, [4, [7,[],[]],
Line 6,452:
;
task</
{{Out}}
$ jq -n -c -r -f Tree_traversal.jq
Line 6,461:
=={{header|Julia}}==
<
Any[]],
Any[]],
Line 6,487:
t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t)
end
</syntaxhighlight>
{{Out}}
Line 6,502:
=={{header|Kotlin}}==
===procedural style===
<
override fun toString() = "$v"
}
Line 6,568:
exec(" postOrder: ", nodes[1], ::postOrder)
exec("level-order: ", nodes[1], ::levelOrder)
}</
{{Out}}
Line 6,579:
===object-oriented style===
<
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)
}
}</
=={{header|Lambdatalk}}==
Line 6,633:
- {A.get index array} gets the value of array at index
</pre>
<
{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>
=={{header|Lingo}}==
<
property _val, _left, _right
Line 6,698:
on getRight (me)
return me._right
end</
<
on inOrder (me, node, l)
Line 6,750:
delete the last char of str
return str
end</
Usage:
<
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]))</
{{Out}}
Line 6,783:
=={{header|Logo}}==
<
to node.left :node
Line 6,839:
in.order :tree [(type ? "| |)] (print)
post.order :tree [(type ? "| |)] (print)
level.order :tree [(type ? "| |)] (print)</
=={{header|Logtalk}}==
<
:- object(tree_traversal).
Line 6,923:
:- end_object.
</syntaxhighlight>
Sample output:
<
| ?- ?- 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>
=={{header|Lua}}==
<
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(), " "))</
=={{header|M2000 Interpreter}}==
Line 6,986:
A tuple is an "auto array" in M2000 Interpreter. (,) is the zero length array.
<
Module CheckIt {
Null=(,)
Line 7,046:
}
CheckIt
</syntaxhighlight>
===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.
<
Module OOP {
\\ Class is a global function (until this module end)
Line 7,135:
}
OOP
</syntaxhighlight>
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)
<
Module OOP {
\\ Class is a global function (until this module end)
Line 7,227:
}
OOP
</syntaxhighlight>
Using Event object as visitor
<
Module OOP {
\\ Class is a global function (until this module end)
Line 7,322:
}
OOP
</syntaxhighlight>
{{out}}
Line 7,333:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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};</
Example:
<
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]]]]</
{{out}}
<pre>{1, 2, 4, 7, 5, 3, 6, 8, 9}
Line 7,355:
=={{header|Mercury}}==
<
:- interface.
Line 7,447:
print_value(V, !IO) :-
io.print(V, !IO),
io.write_string(" ", !IO).</
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 7,455:
=={{header|Nim}}==
<
type
Line 7,499:
echo inorder tree
echo postorder tree
echo levelorder tree</
{{out}}
Line 7,508:
=={{header|Objeck}}==
<
class Test {
Line 7,621:
}
}
</syntaxhighlight>
Output:
Line 7,632:
=={{header|OCaml}}==
<
| 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 ()</
Output:
<pre>1 2 4 7 5 3 6 8 9
Line 7,690:
=={{header|Oforth}}==
<
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
] ;</
{{out}}
Line 7,743:
=={{header|ooRexx}}==
<
one = .Node~new(1);
two = .Node~new(2);
Line 7,827:
nodequeue~queue(next~right)
end
</syntaxhighlight>
Output:
<pre>
Line 7,837:
=={{header|Oz}}==
<
Tree = n(1
n(2
Line 7,894:
{Show {Inorder Tree}}
{Show {Postorder Tree}}
{Show {Levelorder Tree}}</
=={{header|Perl}}==
Tree nodes are represented by 3-element arrays: [0] - the value; [1] - left child; [2] - right child.
<
{
my $t = shift or return ();
Line 7,933:
print "in: @{[inorder($x)]}\n";
print "post: @{[postorder($x)]}\n";
print "depth: @{[depth($x)]}\n";</
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.
<!--<
<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>
<!--</
{{out}}
Line 8,003:
=={{header|PHP}}==
<
private $left;
private $right;
Line 8,104:
$tree->postOrder($arr[1]);
echo "\nlevel-order:\t";
$tree->levelOrder($arr[1]);</
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,112:
=={{header|PicoLisp}}==
<
(when Node
(Fun (car Node))
Line 8,145:
(prin (align -13 (pack Order ":")))
(Order *Tree printsp)
(prinl) )</
Output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,154:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
Tree= [1,
[2,
Line 8,210:
append_dl(X-Y, Y-Z, X-Z).
</syntaxhighlight>
Output :
<pre>?- tree.
Line 8,222:
=={{header|PureBasic}}==
{{works with|PureBasic|4.5+}}
<
value.i
*left.node
Line 8,356:
Input()
CloseConsole()
EndIf</
Sample output:
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,367:
===Python: Procedural===
<
Node = namedtuple('Node', 'data, left, right')
Line 8,438:
print(f"{traversal.__name__:>{w}}:", end=' ')
traversal(tree)
print()</
'''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
<
from sys import stdout
Line 8,514:
stdout.write('\nlevelorder: ')
tree.levelorder(printwithspace)
stdout.write('\n')</
{{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.
<
from itertools import chain
Line 8,741:
if __name__ == '__main__':
main()</
{{Out}}
<pre>Tree traversals - accumulating and folding:
Line 8,758:
=={{header|Qi}}==
<syntaxhighlight lang=qi>
(set *tree* [1 [2 [4 [7]]
[5]]
Line 8,803:
(inorder (value *tree*))
(levelorder (value *tree*))
</syntaxhighlight>
Output:
Line 8,815:
Requires the words at [[Queue/Definition#Quackery]] for <code>level-order</code>.
<
[ ' [ 1
Line 8,861:
tree in-order cr
tree post-order cr
tree level-order cr</
{{out}}
Line 8,872:
=={{header|Racket}}==
<
#lang racket
Line 8,895:
(define (run order)
(printf "~a:" (object-name order))
(order the-tree (
(newline))
(for-each run (list preorder inorder postorder levelorder))
</syntaxhighlight>
Output:
Line 8,910:
=={{header|Raku}}==
(formerly Perl 6)
<
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(" ");</
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 8,975:
=={{header|REBOL}}==
<
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
; "compacted" version
Line 9,022:
]
prin "level-order: " level-order tree
</syntaxhighlight>
{{out}}
<pre>
Line 9,032:
=={{header|REXX}}==
<
/* REXX ***************************************************************
* Tree traversal
Line 9,350:
Say ''
End
Return</
{{out}}
<pre> 1
Line 9,366:
=={{header|Ruby}}==
<
def self.from_array(nested_list)
value, left, right = nested_list
Line 9,405:
root.send(mthd) {|node| print "#{node.value} "}
puts
end</
{{out}}
Line 9,416:
=={{header|Rust}}==
This solution uses iteration (rather than recursion) for all traversal types.
<
#![feature(box_syntax, box_patterns)]
Line 9,592:
}
}
</syntaxhighlight>
Output is same as Ruby et al.
=={{header|Scala}}==
{{works with|Scala|2.11.x}}
<
def preorder(f: IntNode => Unit) {
Line 9,651:
println(s)
}
}</
Output:<pre>
Line 9,661:
=={{header|Scheme}}==
<
(if (null? tree)
'()
Line 9,726:
())))
(demonstration the-task-tree)</
{{out}}
<pre>preorder: 1 2 4 7 5 3 6 8 9
Line 9,734:
=={{header|SequenceL}}==
<
main(args(2)) :=
"preorder: " ++ toString(preOrder(testTree)) ++
Line 9,777:
)
);
</syntaxhighlight>
{{out}}
Output:
Line 9,789:
=={{header|Sidef}}==
{{trans|Perl}}
<
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
}
Line 9,816:
say "in: #{inorder(x)}";
say "post: #{postorder(x)}";
say "depth: #{depth(x)}";</
{{out}}
<pre>
Line 9,835:
'''Object subclass: EmptyNode'''
<
EmptyNode>>accept: aVisitor
Line 9,844:
EmptyNode>>traverse: aVisitorClass do: aBlock
^self accept: (aVisitorClass block: aBlock)
</syntaxhighlight>
'''EmptyNode subclass: Node'''
<
Node>>accept: aVisitor
^aVisitor visit: self
Line 9,882:
Node class>>data: anObject
^self new data: anObject
</syntaxhighlight>
'''Object subclass: Visitor'''
<
visit: aNode
self subclassResponsibility
Line 9,902:
Visitor class>>block: aBlock
^self new block: aBlock
</syntaxhighlight>
'''Visitor subclass: InOrder'''
<
InOrder>>visit: aNode
aNode left accept: self.
block value: aNode.
aNode right accept: self
</syntaxhighlight>
'''Visitor subclass: LevelOrder'''
<
LevelOrder>>visit: aNode
| queue |
Line 9,925:
add: aNode right;
yourself
</syntaxhighlight>
'''Visitor subclass: PostOrder'''
<
PostOrder>>visit: aNode
aNode left accept: self.
aNode right accept: self.
block value: aNode
</syntaxhighlight>
"Visitor subclass: PreOrder"
<
PreOrder>>visit: aNode
block value: aNode.
aNode left accept: self.
aNode right accept: self
</syntaxhighlight>
Execute code in a Workspace:
<
tree := (Node data: 1)
left: ((Node data: 2)
Line 9,962:
tree traverse: LevelOrder do: [:node | Transcript print: node data; space].
Transcript cr.
</syntaxhighlight>
Output in Transcript:
Line 9,971:
=={{header|Swift}}==
<
let value: T
let left: TreeNode?
Line 10,056:
print("level-order: ", terminator: "")
n.levelOrder(function: fn)
print()</
{{out}}
Line 10,068:
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<
# Basic tree data structure stuff...
variable val l r
Line 10,117:
}
}
}</
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:
<
proc Tree nested {
lassign $nested v l r
Line 10,142:
puts "postorder: [Listify $t postorder]"
puts "level-order: [Listify $t levelorder]"
$t destroy</
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.
<
right=()
value=()
Line 10,234:
inorder 1
postorder 1
levelorder 1</
The output:
<
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</
=={{header|Ursala}}==
Line 10,251:
the result on standard output as a
list of lists of naturals.
<
1^:<
Line 10,264:
#cast %nLL
main = <.pre,in,post,lev> tree</
output:
<pre>
Line 10,276:
=={{header|VBA}}==
TreeItem Class Module
<syntaxhighlight lang=VB>
Public Value As Integer
Public LeftChild As TreeItem
Public RightChild As TreeItem
</syntaxhighlight>
Module
<syntaxhighlight lang=VB>
Dim tihead As TreeItem
Line 10,354:
Call LevelOrder(tihead)
End Sub
</syntaxhighlight>
{{out}}
<pre>
Line 10,366:
{{trans|Kotlin}}
The object-oriented version.
<
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() })</
{{out}}
Line 10,443:
=={{header|zkl}}==
<
fcn init(val,[Node]l=Void,[Node]r=Void) { v,left,right=vm.arglist }
}
Line 10,473:
sink
}
}</
It is easy to convert to lazy by replacing "sink.write" with "vm.yield" and wrapping the traversal with a Utils.Generator.
<
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");</
The "apply("v")" extracts the contents of var v from each node.
{{out}}
|