Tree traversal: Difference between revisions

Content added Content deleted
(lang -> syntaxhighlight)
m (syntax highlighting fixup automation)
Line 34: Line 34:
{{trans|Python: Class based}}
{{trans|Python: Class based}}


<syntaxhighlight lang=11l>T Node
<syntaxhighlight lang="11l">T Node
Int data
Int data
Node? left
Node? left
Line 117: Line 117:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64 Assembly>
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deftree64.s */
/* program deftree64.s */
Line 508: Line 508:


=={{header|ACL2}}==
=={{header|ACL2}}==
<syntaxhighlight lang=lisp>(defun flatten-preorder (tree)
<syntaxhighlight lang="lisp">(defun flatten-preorder (tree)
(if (endp tree)
(if (endp tree)
nil
nil
Line 560: Line 560:
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
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}}
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang=Action!>CARD EndProg ;required for ALLOCATE.ACT
<syntaxhighlight 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!
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 821: Line 821:


=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=Ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Containers.Doubly_Linked_Lists;
Line 931: Line 931:


=={{header|Agda}}==
=={{header|Agda}}==
<syntaxhighlight lang=Agda>open import Data.List using (List; _?_; []; concat)
<syntaxhighlight lang="agda">open import Data.List using (List; _?_; []; concat)
open import Data.Nat using (N; suc; zero)
open import Data.Nat using (N; suc; zero)
open import Level using (Level)
open import Level using (Level)
Line 1,017: Line 1,017:


{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
<syntaxhighlight lang=algol68>MODE VALUE = INT;
<syntaxhighlight lang="algol68">MODE VALUE = INT;
PROC value repr = (VALUE value)STRING: whole(value, 0);
PROC value repr = (VALUE value)STRING: whole(value, 0);


Line 1,152: Line 1,152:


Written in Dyalog APL with dfns.
Written in Dyalog APL with dfns.
<syntaxhighlight lang=APL>preorder ? {l r?? ?? ? ? (?r)???(×?r)?(?l)???(×?l)?? ?? ?}
<syntaxhighlight lang="apl">preorder ? {l r?? ?? ? ? (?r)???(×?r)?(?l)???(×?l)?? ?? ?}
inorder ? {l r?? ?? ? ? (?r)???(×?r)?? ???(?l)???(×?l)??}
inorder ? {l r?? ?? ? ? (?r)???(×?r)?? ???(?l)???(×?l)??}
postorder? {l r?? ?? ? ? ? ???(?r)???(×?r)?(?l)???(×?l)??}
postorder? {l r?? ?? ? ? ? ???(?r)???(×?r)?(?l)???(×?l)??}
Line 1,174: Line 1,174:
and empty childL or childR mean and absence of the corresponding child node.
and empty childL or childR mean and absence of the corresponding child node.


<syntaxhighlight lang=APL>tree?1(2(4(7??)?)(5??))(3(6(8??)(9??))?)
<syntaxhighlight lang="apl">tree?1(2(4(7??)?)(5??))(3(6(8??)(9??))?)
visit?{?,(×??)???}
visit?{?,(×??)???}
children?{?¨@(×°?¨)1??}</syntaxhighlight>
children?{?¨@(×°?¨)1??}</syntaxhighlight>
Line 1,198: Line 1,198:
=={{header|AppleScript}}==
=={{header|AppleScript}}==
{{Trans|JavaScript}}(ES6)
{{Trans|JavaScript}}(ES6)
<syntaxhighlight lang=AppleScript>on run
<syntaxhighlight lang="applescript">on run
-- Sample tree of integers
-- Sample tree of integers
set tree to node(1, ¬
set tree to node(1, ¬
Line 1,538: Line 1,538:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 2,022: Line 2,022:


=={{header|ATS}}==
=={{header|ATS}}==
<syntaxhighlight lang=ATS>#include
<syntaxhighlight lang="ats">#include
"share/atspre_staload.hats"
"share/atspre_staload.hats"
//
//
Line 2,129: Line 2,129:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
{{works with|AutoHotkey_L|45}}
<syntaxhighlight lang=AutoHotkey>AddNode(Tree,1,2,3,1) ; Build global Tree
<syntaxhighlight lang="autohotkey">AddNode(Tree,1,2,3,1) ; Build global Tree
AddNode(Tree,2,4,5,2)
AddNode(Tree,2,4,5,2)
AddNode(Tree,3,6,0,3)
AddNode(Tree,3,6,0,3)
Line 2,184: Line 2,184:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=awk>
<syntaxhighlight lang="awk">
function preorder(tree, node, res, child) {
function preorder(tree, node, res, child) {
if (node == "")
if (node == "")
Line 2,277: Line 2,277:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<syntaxhighlight lang=bracmat>(
<syntaxhighlight lang="bracmat">(
( tree
( tree
= 1
= 1
Line 2,320: Line 2,320:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>


Line 2,468: Line 2,468:


=={{header|C sharp}}==
=={{header|C sharp}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 2,546: Line 2,546:
{{libheader|Boost|1.39.0}}
{{libheader|Boost|1.39.0}}


<syntaxhighlight lang=cpp>#include <boost/scoped_ptr.hpp>
<syntaxhighlight lang="cpp">#include <boost/scoped_ptr.hpp>
#include <iostream>
#include <iostream>
#include <queue>
#include <queue>
Line 2,642: Line 2,642:


===Array version===
===Array version===
<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


using namespace std;
using namespace std;
Line 2,714: Line 2,714:
===Modern C++===
===Modern C++===
{{works with|C++14}}
{{works with|C++14}}
<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <memory>
#include <memory>
#include <queue>
#include <queue>
Line 2,819: Line 2,819:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<syntaxhighlight lang=ceylon>import ceylon.collection {
<syntaxhighlight lang="ceylon">import ceylon.collection {
ArrayList
ArrayList
}
}
Line 2,918: Line 2,918:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=clojure>(defn walk [node f order]
<syntaxhighlight lang="clojure">(defn walk [node f order]
(when node
(when node
(doseq [o order]
(doseq [o order]
Line 2,964: Line 2,964:


=={{header|CLU}}==
=={{header|CLU}}==
<syntaxhighlight lang=clu>bintree = cluster [T: type] is leaf, node,
<syntaxhighlight lang="clu">bintree = cluster [T: type] is leaf, node,
pre_order, post_order, in_order, level_order
pre_order, post_order, in_order, level_order
branch = struct[left, right: bintree[T], val: T]
branch = struct[left, right: bintree[T], val: T]
Line 3,065: Line 3,065:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<syntaxhighlight lang=coffeescript>
<syntaxhighlight lang="coffeescript">
# In this example, we don't encapsulate binary trees as objects; instead, we have a
# 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
# convention on how to store them as arrays, and we namespace the functions that
Line 3,124: Line 3,124:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<syntaxhighlight lang=lisp>(defun preorder (node f)
<syntaxhighlight lang="lisp">(defun preorder (node f)
(when node
(when node
(funcall f (first node))
(funcall f (first node))
Line 3,172: Line 3,172:
=={{header|Coq}}==
=={{header|Coq}}==


<syntaxhighlight lang=coq>Require Import Utf8.
<syntaxhighlight lang="coq">Require Import Utf8.
Require Import List.
Require Import List.


Line 3,227: Line 3,227:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|C++}}
{{trans|C++}}
<syntaxhighlight lang=crystal>
<syntaxhighlight lang="crystal">
class Node(T)
class Node(T)
property left : Nil | Node(T)
property left : Nil | Node(T)
Line 3,320: Line 3,320:
=={{header|D}}==
=={{header|D}}==
This code is long because it's very generic.
This code is long because it's very generic.
<syntaxhighlight lang=d>import std.stdio, std.traits;
<syntaxhighlight lang="d">import std.stdio, std.traits;


const final class Node(T) {
const final class Node(T) {
Line 3,406: Line 3,406:
{{trans|Haskell}}
{{trans|Haskell}}
Generic as the first version, but not lazy as the Haskell version.
Generic as the first version, but not lazy as the Haskell version.
<syntaxhighlight lang=d>const struct Node(T) {
<syntaxhighlight lang="d">const struct Node(T) {
T v;
T v;
Node* l, r;
Node* l, r;
Line 3,458: Line 3,458:
===Alternative Lazy Version===
===Alternative Lazy Version===
This version is not complete, it lacks the level order visit.
This version is not complete, it lacks the level order visit.
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.range, std.string;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.string;


const struct Tree(T) {
const struct Tree(T) {
Line 3,530: Line 3,530:
=={{header|E}}==
=={{header|E}}==


<syntaxhighlight lang=e>def btree := [1, [2, [4, [7, null, null],
<syntaxhighlight lang="e">def btree := [1, [2, [4, [7, null, null],
null],
null],
[5, null, null]],
[5, null, null]],
Line 3,582: Line 3,582:


Void-Safety has been disabled for simplicity of the code.
Void-Safety has been disabled for simplicity of the code.
<syntaxhighlight lang=eiffel >note
<syntaxhighlight lang="eiffel ">note
description : "Application for tree traversal demonstration"
description : "Application for tree traversal demonstration"
output : "[
output : "[
Line 3,633: Line 3,633:


end -- class APPLICATION</syntaxhighlight>
end -- class APPLICATION</syntaxhighlight>
<syntaxhighlight lang=eiffel >note
<syntaxhighlight lang="eiffel ">note
description : "A simple node for a binary tree"
description : "A simple node for a binary tree"
libraries : "Relies on LINKED_LIST from EiffelBase"
libraries : "Relies on LINKED_LIST from EiffelBase"
Line 3,763: Line 3,763:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<syntaxhighlight lang=elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import extensions'routines;
import extensions'routines;
import system'collections;
import system'collections;
Line 3,894: Line 3,894:
=={{header|Elisa}}==
=={{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].
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>
<syntaxhighlight lang="elisa">
component BinaryTreeTraversals (Tree, Element);
component BinaryTreeTraversals (Tree, Element);
type Tree;
type Tree;
Line 3,933: Line 3,933:
</syntaxhighlight>
</syntaxhighlight>
Tests
Tests
<syntaxhighlight lang=Elisa>
<syntaxhighlight lang="elisa">
use BinaryTreeTraversals (Tree, integer);
use BinaryTreeTraversals (Tree, integer);


Line 3,957: Line 3,957:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<syntaxhighlight lang=elixir>defmodule Tree_Traversal do
<syntaxhighlight lang="elixir">defmodule Tree_Traversal do
defp tnode, do: {}
defp tnode, do: {}
defp tnode(v), do: {:node, v, {}, {}}
defp tnode(v), do: {:node, v, {}, {}}
Line 4,023: Line 4,023:


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang=erlang>-module(tree_traversal).
<syntaxhighlight lang="erlang">-module(tree_traversal).
-export([main/0]).
-export([main/0]).
-export([preorder/2, inorder/2, postorder/2, levelorder/2]).
-export([preorder/2, inorder/2, postorder/2, levelorder/2]).
Line 4,074: Line 4,074:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<syntaxhighlight lang=euphoria>constant VALUE = 1, LEFT = 2, RIGHT = 3
<syntaxhighlight lang="euphoria">constant VALUE = 1, LEFT = 2, RIGHT = 3


constant tree = {1,
constant tree = {1,
Line 4,149: Line 4,149:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang=fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.IO
open System.IO


Line 4,226: Line 4,226:


=={{header|Factor}}==
=={{header|Factor}}==
<syntaxhighlight lang=factor>USING: accessors combinators deques dlists fry io kernel
<syntaxhighlight lang="factor">USING: accessors combinators deques dlists fry io kernel
math.parser ;
math.parser ;
IN: rosetta.tree-traversal
IN: rosetta.tree-traversal
Line 4,300: Line 4,300:


=={{header|Fantom}}==
=={{header|Fantom}}==
<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
class Tree
class Tree
{
{
Line 4,381: Line 4,381:


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>\ binary tree (dictionary)
<syntaxhighlight lang="forth">\ binary tree (dictionary)
: node ( l r data -- node ) here >r , , , r> ;
: node ( l r data -- node ) here >r , , , r> ;
: leaf ( data -- node ) 0 0 rot node ;
: leaf ( data -- node ) 0 0 rot node ;
Line 4,446: 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.
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 <syntaxhighlight lang=Fortran>
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 <syntaxhighlight lang="fortran">
IF (STYLE.EQ."PRE") CALL OUT(HAS)
IF (STYLE.EQ."PRE") CALL OUT(HAS)
IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE)
IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE)
Line 4,458: 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.
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 <syntaxhighlight lang=Fortran>
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 <syntaxhighlight lang="fortran">
DO GASP = 1,MAXLEVEL
DO GASP = 1,MAXLEVEL
CALL TARZAN(1,HOW)
CALL TARZAN(1,HOW)
Line 4,465: Line 4,465:


===Source===
===Source===
<syntaxhighlight lang=Fortran>
<syntaxhighlight lang="fortran">
MODULE ARAUCARIA !Cunning crosswords, also.
MODULE ARAUCARIA !Cunning crosswords, also.
INTEGER ENUFF !To suit the set example.
INTEGER ENUFF !To suit the set example.
Line 4,687: Line 4,687:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<syntaxhighlight lang=freebasic>
<syntaxhighlight lang="freebasic">
#define NULL 0
#define NULL 0


Line 4,772: Line 4,772:
=={{header|FunL}}==
=={{header|FunL}}==
{{trans|Haskell}}
{{trans|Haskell}}
<syntaxhighlight lang=funl>data Tree = Empty | Node( value, left, right )
<syntaxhighlight lang="funl">data Tree = Empty | Node( value, left, right )


def
def
Line 4,951: Line 4,951:
{{trans|C}}
{{trans|C}}
This is like many examples on this page.
This is like many examples on this page.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 5,046: Line 5,046:
===Flat slice===
===Flat slice===
Alternative representation. Like Wikipedia [http://en.wikipedia.org/wiki/Binary_tree#Arrays Binary tree#Arrays]
Alternative representation. Like Wikipedia [http://en.wikipedia.org/wiki/Binary_tree#Arrays Binary tree#Arrays]
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 5,120: Line 5,120:
=={{header|Groovy}}==
=={{header|Groovy}}==
Uses Groovy '''Node''' and '''NodeBuilder''' classes
Uses Groovy '''Node''' and '''NodeBuilder''' classes
<syntaxhighlight lang=groovy>def preorder;
<syntaxhighlight lang="groovy">def preorder;
preorder = { Node node ->
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
([node] + node.children().collect { preorder(it) }).flatten()
Line 5,157: Line 5,157:


Verify that '''BinaryNodeBuilder''' will not allow a node to have more than 2 children
Verify that '''BinaryNodeBuilder''' will not allow a node to have more than 2 children
<syntaxhighlight lang=groovy>try {
<syntaxhighlight lang="groovy">try {
new BinaryNodeBuilder().'1' {
new BinaryNodeBuilder().'1' {
a {}
a {}
Line 5,169: Line 5,169:


Test case #1 (from the task definition)
Test case #1 (from the task definition)
<syntaxhighlight lang=groovy>// 1
<syntaxhighlight lang="groovy">// 1
// / \
// / \
// 2 3
// 2 3
Line 5,188: Line 5,188:


Test case #2 (tests single right child)
Test case #2 (tests single right child)
<syntaxhighlight lang=groovy>// 1
<syntaxhighlight lang="groovy">// 1
// / \
// / \
// 2 3
// 2 3
Line 5,207: Line 5,207:


Run tests:
Run tests:
<syntaxhighlight lang=groovy>def test = { tree ->
<syntaxhighlight lang="groovy">def test = { tree ->
println "preorder: ${preorder(tree).collect{it.name()}}"
println "preorder: ${preorder(tree).collect{it.name()}}"
println "preorder: ${tree.depthFirst().collect{it.name()}}"
println "preorder: ${tree.depthFirst().collect{it.name()}}"
Line 5,242: Line 5,242:
=={{header|Haskell}}==
=={{header|Haskell}}==
===Left Right nodes===
===Left Right nodes===
<syntaxhighlight lang=haskell>---------------------- TREE TRAVERSAL --------------------
<syntaxhighlight lang="haskell">---------------------- TREE TRAVERSAL --------------------


data Tree a
data Tree a
Line 5,332: Line 5,332:


{{Trans|Python}}
{{Trans|Python}}
<syntaxhighlight lang=haskell>import Data.Bool (bool)
<syntaxhighlight lang="haskell">import Data.Bool (bool)
import Data.Tree (Tree (..), drawForest, drawTree, foldTree)
import Data.Tree (Tree (..), drawForest, drawTree, foldTree)


Line 5,452: Line 5,452:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang=Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]]
showTree(bTree, preorder|inorder|postorder|levelorder)
showTree(bTree, preorder|inorder|postorder|levelorder)
Line 5,495: Line 5,495:


=={{header|Isabelle}}==
=={{header|Isabelle}}==
<syntaxhighlight lang=Isabelle>theory Tree
<syntaxhighlight lang="isabelle">theory Tree
imports Main
imports Main
begin
begin
Line 5,577: Line 5,577:
=={{header|J}}==
=={{header|J}}==


<syntaxhighlight lang=J>preorder=: ]S:0
<syntaxhighlight lang="j">preorder=: ]S:0
postorder=: ([:; postorder&.>@}.) , >@{.
postorder=: ([:; postorder&.>@}.) , >@{.
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
levelorder=: ;@({::L:1 _~ [: (/: #@>) <S:1@{::)
Line 5,584: Line 5,584:
Required example:
Required example:


<syntaxhighlight lang=J>N2=: conjunction def '(<m),(<n),<y'
<syntaxhighlight lang="j">N2=: conjunction def '(<m),(<n),<y'
N1=: adverb def '(<m),<y'
N1=: adverb def '(<m),<y'
L=: adverb def '<m'
L=: adverb def '<m'
Line 5,592: Line 5,592:
This tree is organized in a pre-order fashion
This tree is organized in a pre-order fashion


<syntaxhighlight lang=J> preorder tree
<syntaxhighlight lang="j"> preorder tree
1 2 4 7 5 3 6 8 9</syntaxhighlight>
1 2 4 7 5 3 6 8 9</syntaxhighlight>


post-order is not that much different from pre-order, except that the children must extracted before the parent.
post-order is not that much different from pre-order, except that the children must extracted before the parent.


<syntaxhighlight lang=J> postorder tree
<syntaxhighlight lang="j"> postorder tree
7 4 5 2 8 9 6 3 1</syntaxhighlight>
7 4 5 2 8 9 6 3 1</syntaxhighlight>


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
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


<syntaxhighlight lang=J> inorder tree
<syntaxhighlight lang="j"> inorder tree
7 4 2 5 1 8 6 9 3</syntaxhighlight>
7 4 2 5 1 8 6 9 3</syntaxhighlight>


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.
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.


<syntaxhighlight lang=J> levelorder tree
<syntaxhighlight lang="j"> levelorder tree
1 2 3 4 5 6 7 8 9</syntaxhighlight>
1 2 3 4 5 6 7 8 9</syntaxhighlight>


Line 5,613: Line 5,613:
For J novices, here's the tree instance with a few redundant parenthesis:
For J novices, here's the tree instance with a few redundant parenthesis:


<syntaxhighlight lang=J> tree=: 1 N2 (2 N2 (4 N1 (7 L)) (5 L)) (3 N1 (6 N2 (8 L) (9 L)))</syntaxhighlight>
<syntaxhighlight lang="j"> tree=: 1 N2 (2 N2 (4 N1 (7 L)) (5 L)) (3 N1 (6 N2 (8 L) (9 L)))</syntaxhighlight>


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.)
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: 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:
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:


<syntaxhighlight lang=J>example=:1 8 3 4 7 5 9 6 2,: 0 7 0 8 3 8 7 2 0</syntaxhighlight>
<syntaxhighlight lang="j">example=:1 8 3 4 7 5 9 6 2,: 0 7 0 8 3 8 7 2 0</syntaxhighlight>


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.
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: Line 5,627:
Next, let's define a few utilities:
Next, let's define a few utilities:


<syntaxhighlight lang=J>depth=: +/@((~: , (~: i.@#@{.)~) {:@,)@({~^:a:)
<syntaxhighlight lang="j">depth=: +/@((~: , (~: i.@#@{.)~) {:@,)@({~^:a:)


reorder=:4 :0
reorder=:4 :0
Line 5,651: 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):
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):


<syntaxhighlight lang=J>dataorder=: /:@data reorder ]
<syntaxhighlight lang="j">dataorder=: /:@data reorder ]
levelorder=: /:@depth@parent reorder ]
levelorder=: /:@depth@parent reorder ]


Line 5,709: Line 5,709:
Example use:
Example use:


<syntaxhighlight lang=J> levelorder dataorder example
<syntaxhighlight lang="j"> levelorder dataorder example
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
0 0 0 1 1 2 3 5 5
0 0 0 1 1 2 3 5 5
Line 5,732: Line 5,732:


{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<syntaxhighlight lang=java5>import java.util.*;
<syntaxhighlight lang="java5">import java.util.*;


public class TreeTraversal {
public class TreeTraversal {
Line 5,833: Line 5,833:


{{works with|Java|1.8+}}
{{works with|Java|1.8+}}
<syntaxhighlight lang=java5>import java.util.function.Consumer;
<syntaxhighlight lang="java5">import java.util.function.Consumer;
import java.util.Queue;
import java.util.Queue;
import java.util.LinkedList;
import java.util.LinkedList;
Line 5,970: Line 5,970:
====Iteration====
====Iteration====
inspired by [[#Ruby|Ruby]]
inspired by [[#Ruby|Ruby]]
<syntaxhighlight lang=javascript>function BinaryTree(value, left, right) {
<syntaxhighlight lang="javascript">function BinaryTree(value, left, right) {
this.value = value;
this.value = value;
this.left = left;
this.left = left;
Line 6,015: Line 6,015:
(for binary trees consisting of nested lists)
(for binary trees consisting of nested lists)


<syntaxhighlight lang=javascript>(function () {
<syntaxhighlight lang="javascript">(function () {


function preorder(n) {
function preorder(n) {
Line 6,120: Line 6,120:
|}
|}


<syntaxhighlight lang=JavaScript>[["Traversal","Nodes visited"],
<syntaxhighlight 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]],
["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]]]</syntaxhighlight>
["postorder",[7,4,5,2,8,9,6,3,1]],["levelorder",[1,2,3,4,5,6,7,8,9]]]</syntaxhighlight>
Line 6,132: Line 6,132:




<syntaxhighlight lang=JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {
'use strict';
'use strict';


Line 6,254: Line 6,254:
})();</syntaxhighlight>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<syntaxhighlight lang=JavaScript>{"preorder":[1, 2, 4, 7, 5, 3, 6, 8, 9],
<syntaxhighlight lang="javascript">{"preorder":[1, 2, 4, 7, 5, 3, 6, 8, 9],
"inorder":[7, 4, 2, 5, 1, 8, 6, 9, 3],
"inorder":[7, 4, 2, 5, 1, 8, 6, 9, 3],
"postorder":[7, 4, 5, 2, 8, 9, 6, 3, 1],
"postorder":[7, 4, 5, 2, 8, 9, 6, 3, 1],
Line 6,263: Line 6,263:
{{Trans|Haskell}}
{{Trans|Haskell}}
{{Trans|Python}}
{{Trans|Python}}
<syntaxhighlight lang=JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 6,408: Line 6,408:


The implementation assumes an array structured recursively as [ node, left, right ], where "left" and "right" may be [] or null equivalently.
The implementation assumes an array structured recursively as [ node, left, right ], where "left" and "right" may be [] or null equivalently.
<syntaxhighlight lang=jq>def preorder:
<syntaxhighlight lang="jq">def preorder:
if length == 0 then empty
if length == 0 then empty
else .[0], (.[1]|preorder), (.[2]|preorder)
else .[0], (.[1]|preorder), (.[2]|preorder)
Line 6,436: Line 6,436:
</syntaxhighlight>
</syntaxhighlight>
'''The task''':
'''The task''':
<syntaxhighlight lang=jq>def task:
<syntaxhighlight lang="jq">def task:
# [node, left, right]
# [node, left, right]
def atree: [1, [2, [4, [7,[],[]],
def atree: [1, [2, [4, [7,[],[]],
Line 6,461: Line 6,461:


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang=Julia>tree = Any[1, Any[2, Any[4, Any[7, Any[],
<syntaxhighlight lang="julia">tree = Any[1, Any[2, Any[4, Any[7, Any[],
Any[]],
Any[]],
Any[]],
Any[]],
Line 6,502: Line 6,502:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
===procedural style===
===procedural style===
<syntaxhighlight lang=scala>data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
<syntaxhighlight lang="scala">data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = "$v"
override fun toString() = "$v"
}
}
Line 6,579: Line 6,579:


===object-oriented style===
===object-oriented style===
<syntaxhighlight lang=scala>fun main(args: Array<String>) {
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = " $v"
override fun toString() = " $v"
Line 6,633: Line 6,633:
- {A.get index array} gets the value of array at index
- {A.get index array} gets the value of array at index
</pre>
</pre>
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
{def walk
{def walk


Line 6,671: Line 6,671:


=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang=lingo>-- parent script "BinaryTreeNode"
<syntaxhighlight lang="lingo">-- parent script "BinaryTreeNode"


property _val, _left, _right
property _val, _left, _right
Line 6,700: Line 6,700:
end</syntaxhighlight>
end</syntaxhighlight>


<syntaxhighlight lang=lingo>-- parent script "BinaryTreeTraversal"
<syntaxhighlight lang="lingo">-- parent script "BinaryTreeTraversal"


on inOrder (me, node, l)
on inOrder (me, node, l)
Line 6,753: Line 6,753:


Usage:
Usage:
<syntaxhighlight lang=lingo>-- create the tree
<syntaxhighlight lang="lingo">-- create the tree
l = []
l = []
repeat with i = 1 to 10
repeat with i = 1 to 10
Line 6,783: Line 6,783:


=={{header|Logo}}==
=={{header|Logo}}==
<syntaxhighlight lang=logo>; nodes are [data left right], use "first" to get data
<syntaxhighlight lang="logo">; nodes are [data left right], use "first" to get data


to node.left :node
to node.left :node
Line 6,842: Line 6,842:


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<syntaxhighlight lang=logtalk>
<syntaxhighlight lang="logtalk">
:- object(tree_traversal).
:- object(tree_traversal).


Line 6,925: Line 6,925:
</syntaxhighlight>
</syntaxhighlight>
Sample output:
Sample output:
<syntaxhighlight lang=text>
<syntaxhighlight lang="text">
| ?- ?- tree_traversal::orders.
| ?- ?- tree_traversal::orders.
Pre-order: 1 2 4 7 5 3 6 8 9
Pre-order: 1 2 4 7 5 3 6 8 9
Line 6,935: Line 6,935:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=Lua>-- Utility
<syntaxhighlight lang="lua">-- Utility
local function append(t1, t2)
local function append(t1, t2)
for _, v in ipairs(t2) do
for _, v in ipairs(t2) do
Line 6,986: Line 6,986:
A tuple is an "auto array" in M2000 Interpreter. (,) is the zero length array.
A tuple is an "auto array" in M2000 Interpreter. (,) is the zero length array.


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Module CheckIt {
Null=(,)
Null=(,)
Line 7,051: Line 7,051:
The "as pointer" is optional, but we can use type check if we want.
The "as pointer" is optional, but we can use type check if we want.


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module OOP {
Module OOP {
\\ Class is a global function (until this module end)
\\ Class is a global function (until this module end)
Line 7,140: Line 7,140:
also i put a visitor as a call back (a lambda function called as module)
also i put a visitor as a call back (a lambda function called as module)


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module OOP {
Module OOP {
\\ Class is a global function (until this module end)
\\ Class is a global function (until this module end)
Line 7,231: Line 7,231:
Using Event object as visitor
Using Event object as visitor


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Module OOP {
Module OOP {
\\ Class is a global function (until this module end)
\\ Class is a global function (until this module end)
Line 7,333: Line 7,333:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=mathematica>preorder[a_Integer] := a;
<syntaxhighlight lang="mathematica">preorder[a_Integer] := a;
preorder[a_[b__]] := Flatten@{a, preorder /@ {b}};
preorder[a_[b__]] := Flatten@{a, preorder /@ {b}};
inorder[a_Integer] := a;
inorder[a_Integer] := a;
Line 7,344: Line 7,344:


Example:
Example:
<syntaxhighlight lang=mathematica>preorder[1[2[4[7], 5], 3[6[8, 9]]]]
<syntaxhighlight lang="mathematica">preorder[1[2[4[7], 5], 3[6[8, 9]]]]
inorder[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]]]]
postorder[1[2[4[7], 5], 3[6[8, 9]]]]
Line 7,355: Line 7,355:


=={{header|Mercury}}==
=={{header|Mercury}}==
<syntaxhighlight lang=mercury>:- module tree_traversal.
<syntaxhighlight lang="mercury">:- module tree_traversal.
:- interface.
:- interface.


Line 7,455: Line 7,455:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import deques
<syntaxhighlight lang="nim">import deques


type
type
Line 7,508: Line 7,508:


=={{header|Objeck}}==
=={{header|Objeck}}==
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
??use Collection;
??use Collection;


Line 7,632: Line 7,632:


=={{header|OCaml}}==
=={{header|OCaml}}==
<syntaxhighlight lang=ocaml>type 'a tree = Empty
<syntaxhighlight lang="ocaml">type 'a tree = Empty
| Node of 'a * 'a tree * 'a tree
| Node of 'a * 'a tree * 'a tree


Line 7,690: Line 7,690:
=={{header|Oforth}}==
=={{header|Oforth}}==


<syntaxhighlight lang=Oforth>Object Class new: Tree(v, l, r)
<syntaxhighlight lang="oforth">Object Class new: Tree(v, l, r)


Tree method: initialize(v, l, r) v := v l := l r := r ;
Tree method: initialize(v, l, r) v := v l := l r := r ;
Line 7,743: Line 7,743:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="oorexx">
one = .Node~new(1);
one = .Node~new(1);
two = .Node~new(2);
two = .Node~new(2);
Line 7,837: Line 7,837:


=={{header|Oz}}==
=={{header|Oz}}==
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
Tree = n(1
Tree = n(1
n(2
n(2
Line 7,898: Line 7,898:
=={{header|Perl}}==
=={{header|Perl}}==
Tree nodes are represented by 3-element arrays: [0] - the value; [1] - left child; [2] - right child.
Tree nodes are represented by 3-element arrays: [0] - the value; [1] - left child; [2] - right child.
<syntaxhighlight lang=perl>sub preorder
<syntaxhighlight lang="perl">sub preorder
{
{
my $t = shift or return ();
my $t = shift or return ();
Line 7,945: 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.
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.


<!--<syntaxhighlight lang=Phix>-->
<!--<syntaxhighlight 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>
<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 8,003: Line 8,003:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=PHP>class Node {
<syntaxhighlight lang="php">class Node {
private $left;
private $left;
private $right;
private $right;
Line 8,112: Line 8,112:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(de preorder (Node Fun)
<syntaxhighlight lang="picolisp">(de preorder (Node Fun)
(when Node
(when Node
(Fun (car Node))
(Fun (car Node))
Line 8,154: Line 8,154:
=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<syntaxhighlight lang=Prolog>tree :-
<syntaxhighlight lang="prolog">tree :-
Tree= [1,
Tree= [1,
[2,
[2,
Line 8,222: Line 8,222:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{works with|PureBasic|4.5+}}
{{works with|PureBasic|4.5+}}
<syntaxhighlight lang=PureBasic>Structure node
<syntaxhighlight lang="purebasic">Structure node
value.i
value.i
*left.node
*left.node
Line 8,367: Line 8,367:
===Python: Procedural===
===Python: Procedural===


<syntaxhighlight lang=python>from collections import namedtuple
<syntaxhighlight lang="python">from collections import namedtuple
Node = namedtuple('Node', 'data, left, right')
Node = namedtuple('Node', 'data, left, right')
Line 8,454: Line 8,454:


Subclasses a namedtuple adding traversal methods that apply a visitor function to data at nodes of the tree in order
Subclasses a namedtuple adding traversal methods that apply a visitor function to data at nodes of the tree in order
<syntaxhighlight lang=python>from collections import namedtuple
<syntaxhighlight lang="python">from collections import namedtuple
from sys import stdout
from sys import stdout
Line 8,531: 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.
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.


<syntaxhighlight lang=python>'''Tree traversals'''
<syntaxhighlight lang="python">'''Tree traversals'''


from itertools import chain
from itertools import chain
Line 8,758: Line 8,758:


=={{header|Qi}}==
=={{header|Qi}}==
<syntaxhighlight lang=qi>
<syntaxhighlight lang="qi">
(set *tree* [1 [2 [4 [7]]
(set *tree* [1 [2 [4 [7]]
[5]]
[5]]
Line 8,815: Line 8,815:
Requires the words at [[Queue/Definition#Quackery]] for <code>level-order</code>.
Requires the words at [[Queue/Definition#Quackery]] for <code>level-order</code>.


<syntaxhighlight lang=Quackery> [ this ] is nil ( --> [ )
<syntaxhighlight lang="quackery"> [ this ] is nil ( --> [ )


[ ' [ 1
[ ' [ 1
Line 8,872: Line 8,872:
=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 8,910: Line 8,910:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<syntaxhighlight lang=perl6>class TreeNode {
<syntaxhighlight lang="raku" line>class TreeNode {
has TreeNode $.parent;
has TreeNode $.parent;
has TreeNode $.left;
has TreeNode $.left;
Line 8,975: Line 8,975:


=={{header|REBOL}}==
=={{header|REBOL}}==
<syntaxhighlight lang=REBOL>
<syntaxhighlight lang="rebol">
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
; "compacted" version
; "compacted" version
Line 9,032: Line 9,032:


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>
<syntaxhighlight lang="rexx">
/* REXX ***************************************************************
/* REXX ***************************************************************
* Tree traversal
* Tree traversal
Line 9,366: Line 9,366:


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang=ruby>BinaryTreeNode = Struct.new(:value, :left, :right) do
<syntaxhighlight lang="ruby">BinaryTreeNode = Struct.new(:value, :left, :right) do
def self.from_array(nested_list)
def self.from_array(nested_list)
value, left, right = nested_list
value, left, right = nested_list
Line 9,416: Line 9,416:
=={{header|Rust}}==
=={{header|Rust}}==
This solution uses iteration (rather than recursion) for all traversal types.
This solution uses iteration (rather than recursion) for all traversal types.
<syntaxhighlight lang=Rust>
<syntaxhighlight lang="rust">
#![feature(box_syntax, box_patterns)]
#![feature(box_syntax, box_patterns)]


Line 9,597: Line 9,597:
=={{header|Scala}}==
=={{header|Scala}}==
{{works with|Scala|2.11.x}}
{{works with|Scala|2.11.x}}
<syntaxhighlight lang=Scala>case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) {
<syntaxhighlight lang="scala">case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) {


def preorder(f: IntNode => Unit) {
def preorder(f: IntNode => Unit) {
Line 9,661: Line 9,661:


=={{header|Scheme}}==
=={{header|Scheme}}==
<syntaxhighlight lang=scheme>(define (preorder tree)
<syntaxhighlight lang="scheme">(define (preorder tree)
(if (null? tree)
(if (null? tree)
'()
'()
Line 9,734: Line 9,734:


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<syntaxhighlight lang=sequenceL>
<syntaxhighlight lang="sequencel">
main(args(2)) :=
main(args(2)) :=
"preorder: " ++ toString(preOrder(testTree)) ++
"preorder: " ++ toString(preOrder(testTree)) ++
Line 9,789: Line 9,789:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<syntaxhighlight lang=ruby>func preorder(t) {
<syntaxhighlight lang="ruby">func preorder(t) {
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
}
}
Line 9,835: Line 9,835:


'''Object subclass: EmptyNode'''
'''Object subclass: EmptyNode'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
EmptyNode>>accept: aVisitor
EmptyNode>>accept: aVisitor


Line 9,847: Line 9,847:


'''EmptyNode subclass: Node'''
'''EmptyNode subclass: Node'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
Node>>accept: aVisitor
Node>>accept: aVisitor
^aVisitor visit: self
^aVisitor visit: self
Line 9,885: Line 9,885:


'''Object subclass: Visitor'''
'''Object subclass: Visitor'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
visit: aNode
visit: aNode
self subclassResponsibility
self subclassResponsibility
Line 9,905: Line 9,905:


'''Visitor subclass: InOrder'''
'''Visitor subclass: InOrder'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
InOrder>>visit: aNode
InOrder>>visit: aNode
aNode left accept: self.
aNode left accept: self.
Line 9,913: Line 9,913:


'''Visitor subclass: LevelOrder'''
'''Visitor subclass: LevelOrder'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
LevelOrder>>visit: aNode
LevelOrder>>visit: aNode
| queue |
| queue |
Line 9,928: Line 9,928:


'''Visitor subclass: PostOrder'''
'''Visitor subclass: PostOrder'''
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
PostOrder>>visit: aNode
PostOrder>>visit: aNode
aNode left accept: self.
aNode left accept: self.
Line 9,936: Line 9,936:


"Visitor subclass: PreOrder"
"Visitor subclass: PreOrder"
<syntaxhighlight lang=smalltalk>"Protocol: visiting"
<syntaxhighlight lang="smalltalk">"Protocol: visiting"
PreOrder>>visit: aNode
PreOrder>>visit: aNode
block value: aNode.
block value: aNode.
Line 9,944: Line 9,944:


Execute code in a Workspace:
Execute code in a Workspace:
<syntaxhighlight lang=smalltalk>| tree |
<syntaxhighlight lang="smalltalk">| tree |
tree := (Node data: 1)
tree := (Node data: 1)
left: ((Node data: 2)
left: ((Node data: 2)
Line 9,971: Line 9,971:


=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang=swift>class TreeNode<T> {
<syntaxhighlight lang="swift">class TreeNode<T> {
let value: T
let value: T
let left: TreeNode?
let left: TreeNode?
Line 10,068: Line 10,068:
=={{header|Tcl}}==
=={{header|Tcl}}==
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<syntaxhighlight lang=tcl>oo::class create tree {
<syntaxhighlight lang="tcl">oo::class create tree {
# Basic tree data structure stuff...
# Basic tree data structure stuff...
variable val l r
variable val l r
Line 10,121: Line 10,121:


Demo code to satisfy the official challenge instance:
Demo code to satisfy the official challenge instance:
<syntaxhighlight lang=tcl># Helpers to make construction and listing of a whole tree simpler
<syntaxhighlight lang="tcl"># Helpers to make construction and listing of a whole tree simpler
proc Tree nested {
proc Tree nested {
lassign $nested v l r
lassign $nested v l r
Line 10,151: Line 10,151:
=={{header|UNIX Shell}}==
=={{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.
Bash (also "sh" on most Unix systems) has arrays. We implement a node as an association between three arrays: left, right, and value.
<syntaxhighlight lang=bash>left=()
<syntaxhighlight lang="bash">left=()
right=()
right=()
value=()
value=()
Line 10,236: Line 10,236:
levelorder 1</syntaxhighlight>
levelorder 1</syntaxhighlight>
The output:
The output:
<syntaxhighlight lang=bash>preorder: 1 2 4 7 5 3 6 8 9
<syntaxhighlight lang="bash">preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
postorder: 7 4 5 2 8 9 6 3 1
Line 10,251: Line 10,251:
the result on standard output as a
the result on standard output as a
list of lists of naturals.
list of lists of naturals.
<syntaxhighlight lang=Ursala>tree =
<syntaxhighlight lang="ursala">tree =


1^:<
1^:<
Line 10,276: Line 10,276:
=={{header|VBA}}==
=={{header|VBA}}==
TreeItem Class Module
TreeItem Class Module
<syntaxhighlight lang=VB>
<syntaxhighlight lang="vb">
Public Value As Integer
Public Value As Integer
Public LeftChild As TreeItem
Public LeftChild As TreeItem
Line 10,282: Line 10,282:
</syntaxhighlight>
</syntaxhighlight>
Module
Module
<syntaxhighlight lang=VB>
<syntaxhighlight lang="vb">
Dim tihead As TreeItem
Dim tihead As TreeItem


Line 10,366: Line 10,366:
{{trans|Kotlin}}
{{trans|Kotlin}}
The object-oriented version.
The object-oriented version.
<syntaxhighlight lang=ecmascript>class Node {
<syntaxhighlight lang="ecmascript">class Node {
construct new(v) {
construct new(v) {
_v = v
_v = v
Line 10,443: Line 10,443:


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>class Node{ var [mixin=Node]left,right; var v;
<syntaxhighlight 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 }
fcn init(val,[Node]l=Void,[Node]r=Void) { v,left,right=vm.arglist }
}
}
Line 10,475: Line 10,475:
}</syntaxhighlight>
}</syntaxhighlight>
It is easy to convert to lazy by replacing "sink.write" with "vm.yield" and wrapping the traversal with a Utils.Generator.
It is easy to convert to lazy by replacing "sink.write" with "vm.yield" and wrapping the traversal with a Utils.Generator.
<syntaxhighlight lang=zkl>t:=BTree(Node(1,
<syntaxhighlight lang="zkl">t:=BTree(Node(1,
Node(2,
Node(2,
Node(4,Node(7)),
Node(4,Node(7)),