Skip to content

Commit 2000ab3

Browse files
lazypropAmarasstormoficejiegilletleios
authoredOct 25, 2021
Tree Traversal: Output Standardization (#857)
* pep8ify python * rename Tree_example.py * standardize python output * standardize c output * standardize c++ output * standardize rust output * standardize javascript output * standardize julia output * Standardized Coconut output * fix coconut * standardize go output * standardize common lisp output * Verlet Integration: Output standardization (#855) * Standardize julia output * Standardize kotlin output This also fixes a previous bug, which caused the time and velocity values to not get printed correctly. * Standardized c output * Standardized cpp output * Standardized lisp output * Standardized fortran output I was not able to prevent the preceding whitespaces, but they can just be trimmed. * Standardized go output * Standardized java output * Standardize javascript output * Standardize nim output * Standardize python output * Standardize ruby output As the original implementation only returned the time and not the velocity, the code needed to be adjusted a bit. Now it returns the two values as an array which gets deconstructed and printed. * Standardize rust output * Standardize swift output * Standardized haskell output * Standardized haskell output (no quote marks) * attempt at fix for asm Co-authored-by: Jérémie Gillet <jie.gillet@gmail.com> Co-authored-by: James Schloss <jrs.schloss@gmail.com> * standardize php output * standardize swift output * removed outdated comments in Coconut implementation * standardize haskell output * Fix asm exit codes (#858) * standardize crystal output * Flood fill in Coconut (#836) * Added Barnsley fern in Coconut (+ .editorconfig for Coconut) (#814) * Added the Jarvis march in Coconut (#734) * Fix minor typo * Change folder structure of convolutions (#861) This puts every chapters' code into its own directory, which is useful for automatic validation. * standardize csharp output * standardize java output * fix php line numbers and python filename * fix coconut and python line numbers * fix minor bug in C * fix labels and minor bug in go * minor label fix in python * Huffman encoding in Coconut (#732) * Update README.md Changing readme link to reflect change in twitch url * Add C# implemenation for 1D Convolutions (#846) * Add C# implemenation for 1D Convolutions * Fix off by one error and julia line numbers * Fix off by one error for linear convolutions * Fix trailing zero * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Update contents/convolutions/code/csharp/1DConvolution.cs Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * Add trailing new line Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> * IFS Common Lisp implementation (#722) * first working version * cleaned up the chaos-game function and added some helpfull comments * changed the .md file and upped iterations * Skeleton of the final solution * Update contents/IFS/IFS.md Co-authored-by: Eric Berquist <eric.berquist@gmail.com> Co-authored-by: James Schloss <jrs.schloss@gmail.com> Co-authored-by: Eric Berquist <eric.berquist@gmail.com> * added MonteCarlo in PowerShell (#760) * Add Rust implementation for The Barnsley Fern (#818) * Add Rust implementation for The Barnsley Fern * Change operators constants and add Cargo.toml * Fix bug in matrix multiplication Co-authored-by: James Schloss <jrs.schloss@gmail.com> * changing barnsley.md to read the correct coconut file (#867) * added approximate counting implementation in python (#866) * added approximate counting implementation in python * Update approximate_counting.py * updating approximate_counting.py * removed redundancies * fixing linking issues in convolution chapter (#868) * Add initial devcontainer (#862) * small changes to convolutional theorem chapter and code to make things more reproduceable (#872) * added convolutional theorem implementation in python (#869) * added convolutional theorem implementation in python * fixed chapter linking * added comments to the code * changed random distribution to sawtooth * corrected previous commit * fixed comments Co-authored-by: James Schloss <jrs.schloss@gmail.com> * Use `[#]\n` instead of `[#]` for human readable output (#873) * Add approximate counting algorithm in C (#844) * Add approximate counting algorithm in C * Fix typo Co-authored-by: stormofice <58337328+stormofice@users.noreply.github.com> Co-authored-by: stormofice <58337328+stormofice@users.noreply.github.com> Co-authored-by: James Schloss <jrs.schloss@gmail.com> * added 1d convolution implementation in python (#874) * added 1d convolution implementation in python * fixed some mistakes in the code so it outputs correct results * making the code look better * spacing code properly for readability * fixing 1d convolution markdown file (#879) * Add racket setup to devcontainer (#875) * Normalize inputs for scheme euclid algorithm (#878) Change inputs to make it consistent with other examples. * Add initial setup for Swift in devcontainer (#880) * Add scheme setup to devcontainer (#876) * Clean up Monte Carlo integration in Racket (#781) * Clean up Monte Carlo integration in Racket * Add blank lines in Monte Carlo integration in Clojure * Change Racket lang include from lisp to racket * Add C++ code for Flood Fill algorithm (#860) * fixing chapter to use split-op code (#888) * use [#]\n for readability * Implemented stacks and queues in Java (#897) * Java tree traversal: updated dfsRecursiveInOrderBinary (#899) * Tree traversal in smalltalk (#453) * fixed print statements (#901) * Fixes in PATH that make dlang, emojicode and factor usable (#890) * fixing huffman encoding for Julia and adding Test (#828) * JavaScript tree traversal: updated dfsInorder (#902) * julia: change printf to print * pep8ify python * rename Tree_example.py * standardize python output * standardize c output * standardize c++ output * standardize rust output * standardize javascript output Resolved conflict with master (by Amaras) * standardize julia output Resolved conflict with master (by Amaras) * Standardized Coconut output * fix coconut * standardize go output * standardize common lisp output * standardize php output * standardize swift output * removed outdated comments in Coconut implementation * standardize haskell output * standardize crystal output * standardize csharp output * standardize java output Resolved the conflict with fixing dfs * fix php line numbers and python filename * fix coconut and python line numbers * fix minor bug in C * fix labels and minor bug in go * minor label fix in python * use [#]\n for readability * julia: change printf to print * update Tree.java. remove MainClass.java Co-authored-by: Sammy Plat <amaras@vivaldi.net> Co-authored-by: stormofice <58337328+stormofice@users.noreply.github.com> Co-authored-by: Jérémie Gillet <jie.gillet@gmail.com> Co-authored-by: James Schloss <jrs.schloss@gmail.com> Co-authored-by: Eric Berquist <eric.berquist@gmail.com> Co-authored-by: Trashtalk217 <trashtalk217@gmail.com> Co-authored-by: PaddyKe <34421580+PaddyKe@users.noreply.github.com> Co-authored-by: Dimitri Belopopsky <ShadowMitia@users.noreply.github.com> Co-authored-by: Ayman Lafaz <ayman.lafaz@um5r.ac.ma> Co-authored-by: Nicholas Tindle <nicktindle@outlook.com> Co-authored-by: Mahdi <24981501+mahdisarikhani@users.noreply.github.com> Co-authored-by: Henrik Christensen <sensen1695@hotmail.com> Co-authored-by: Neverik <neverliberty@gmail.com>
1 parent cf56e67 commit 2000ab3

File tree

20 files changed

+442
-356
lines changed

20 files changed

+442
-356
lines changed
 

‎contents/tree_traversal/code/c++/tree_example.cpp

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ struct node {
1717
// Simple recursive scheme for DFS
1818
void dfs_recursive(node const& n) {
1919
// Here we are doing something...
20-
std::cout << n.value << '\n';
20+
std::cout << n.value << ' ';
2121
for (auto const& child : n.children) {
2222
dfs_recursive(child);
2323
}
@@ -27,23 +27,23 @@ void dfs_recursive_postorder(node const& n) {
2727
for (auto const& child : n.children) {
2828
dfs_recursive_postorder(child);
2929
}
30-
std::cout << n.value << '\n';
30+
std::cout << n.value << ' ';
3131
}
3232

3333

3434
void dfs_recursive_inorder_btree(node const& n) {
3535
switch (n.children.size()) {
3636
case 2:
3737
dfs_recursive_inorder_btree(n.children[0]);
38-
std::cout << n.value << '\n';
38+
std::cout << n.value << ' ';
3939
dfs_recursive_inorder_btree(n.children[1]);
4040
break;
4141
case 1:
4242
dfs_recursive_inorder_btree(n.children[0]);
43-
std::cout << n.value << '\n';
43+
std::cout << n.value << ' ';
4444
break;
4545
case 0:
46-
std::cout << n.value << '\n';
46+
std::cout << n.value << ' ';
4747
break;
4848
default:
4949
std::cout << "This is not a binary tree.\n";
@@ -61,7 +61,7 @@ void dfs_stack(node const& n) {
6161
while (stack.size() > 0) {
6262
auto const& temp = *stack.top();
6363
stack.pop();
64-
std::cout << temp.value << '\n';
64+
std::cout << temp.value << ' ';
6565

6666
for (auto const& child : temp.children) {
6767
stack.push(&child);
@@ -78,7 +78,7 @@ void bfs_queue(node const& n) {
7878
auto const& temp = *queue.front();
7979
queue.pop();
8080

81-
std::cout << temp.value << '\n';
81+
std::cout << temp.value << ' ';
8282
for (auto const& child : temp.children) {
8383
queue.push(&child);
8484
}
@@ -100,18 +100,23 @@ node create_tree(size_t num_row, size_t num_child) {
100100

101101
int main() {
102102
// Creating Tree in main
103-
auto root = create_tree(3, 3);
103+
auto root = create_tree(2, 3);
104104
auto binary_root = create_tree(3, 2);
105-
std::cout << "DFS recursive:\n";
105+
std::cout << "[#]\nRecursive DFS:\n";
106106
dfs_recursive(root);
107-
std::cout << "DFS post order recursive:\n";
107+
std::cout << '\n';
108+
std::cout << "[#]\nRecursive Postorder DFS:\n";
108109
dfs_recursive_postorder(root);
109-
std::cout << "DFS inorder binary tree:\n";
110-
dfs_recursive_inorder_btree(binary_root);
111-
std::cout << "DFS stack:\n";
110+
std::cout << '\n';
111+
std::cout << "[#]\nStack-based DFS:\n";
112112
dfs_stack(root);
113-
std::cout << "BFS queue:\n";
113+
std::cout << '\n';
114+
std::cout << "[#]\nQueue-based BFS:\n";
114115
bfs_queue(root);
116+
std::cout << '\n';
117+
std::cout << "[#]\nRecursive Inorder DFS for Binary Tree:\n";
118+
dfs_recursive_inorder_btree(binary_root);
119+
std::cout << '\n';
115120

116121
return 0;
117122
}

‎contents/tree_traversal/code/c/tree_traversal.c

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ void destroy_tree(struct node n) {
3535
}
3636

3737
void dfs_recursive(struct node n) {
38-
printf("%d\n", n.id);
38+
printf("%d ", n.id);
3939

4040
if (n.children) {
4141
for (size_t i = 0; i < n.children_size; ++i) {
@@ -49,22 +49,22 @@ void dfs_recursive_postorder(struct node n) {
4949
dfs_recursive_postorder(n.children[i]);
5050
}
5151

52-
printf("%d\n", n.id);
52+
printf("%d ", n.id);
5353
}
5454

5555
void dfs_recursive_inorder_btree(struct node n) {
5656
switch (n.children_size) {
5757
case 2:
5858
dfs_recursive_inorder_btree(n.children[0]);
59-
printf("%d\n", n.id);
59+
printf("%d ", n.id);
6060
dfs_recursive_inorder_btree(n.children[1]);
6161
break;
6262
case 1:
6363
dfs_recursive_inorder_btree(n.children[0]);
64-
printf("%d\n", n.id);
64+
printf("%d ", n.id);
6565
break;
6666
case 0:
67-
printf("%d\n", n.id);
67+
printf("%d ", n.id);
6868
break;
6969
default:
7070
printf("This is not a binary tree.\n");
@@ -83,7 +83,7 @@ void dfs_stack(struct node n) {
8383
break;
8484
}
8585

86-
printf("%d\n", tmp->id);
86+
printf("%d ", tmp->id);
8787
for (size_t i = 0; i < tmp->children_size; ++i) {
8888
stack_push(&stk, &tmp->children[i]);
8989
}
@@ -103,7 +103,7 @@ void bfs_queue(struct node n) {
103103
break;
104104
}
105105

106-
printf("%d\n", tmp->id);
106+
printf("%d ", tmp->id);
107107
for (size_t i = 0; i < tmp->children_size; ++i) {
108108
enqueue(&q, &tmp->children[i]);
109109
}
@@ -113,9 +113,31 @@ void bfs_queue(struct node n) {
113113
}
114114

115115
int main() {
116-
struct node root = create_tree(3, 3);
116+
struct node root = create_tree(2, 3);
117+
118+
printf("[#]\nRecursive DFS:\n");
119+
dfs_recursive(root);
120+
printf("\n");
121+
122+
printf("[#]\nRecursive Postorder DFS:\n");
123+
dfs_recursive_postorder(root);
124+
printf("\n");
125+
126+
printf("[#]\nStack-based DFS:\n");
127+
dfs_stack(root);
128+
printf("\n");
129+
130+
printf("[#]\nQueue-based BFS:\n");
117131
bfs_queue(root);
132+
printf("\n");
133+
118134
destroy_tree(root);
135+
struct node root_binary = create_tree(3, 2);
119136

137+
printf("[#]\nRecursive Inorder DFS for Binary Tree:\n");
138+
dfs_recursive_inorder_btree(root_binary);
139+
printf("\n");
140+
141+
destroy_tree(root_binary);
120142
return 0;
121143
}

‎contents/tree_traversal/code/clisp/tree-traversal.lisp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,36 +58,41 @@
5858
(defun make-tree (num-rows num-child)
5959
"Creates a simple tree, where every node has 'num-child' children and is 'num-rows' deep."
6060
;; A tree with 0 rows can't be created.
61-
(if (eql num-rows 1)
61+
(if (eql num-rows 0)
6262
(make-node
63-
:data 1
63+
:data 0
6464
:children nil)
6565
(make-node
6666
:data num-rows
6767
:children (loop repeat num-child collect (make-tree (1- num-rows) num-child)))))
6868

6969
;; A tree for testing
70-
(defvar tree (make-tree 3 3))
70+
(defvar tree (make-tree 2 3))
7171

7272
;; A binary tree for testing
7373
(defvar binary-tree (make-tree 3 2))
7474

7575
;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1
76+
(format t "[#]~%Recursive DFS:~%")
7677
(dfs-recursive tree)
7778
(format t "~%")
7879

7980
;; Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3
81+
(format t "[#]~%Recursive Postorder DFS:~%")
8082
(dfs-recursive-postorder tree)
8183
(format t "~%")
8284

83-
;; Should print: 1 2 1 3 1 2 1
84-
(dfs-recursive-inorder-btree binary-tree)
85-
(format t "~%")
86-
8785
;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1
86+
(format t "[#]~%Stack-based DFS:~%")
8887
(dfs-stack tree)
8988
(format t "~%")
9089

9190
;; Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1
91+
(format t "[#]~%Queue-based BFS:~%")
9292
(bfs-queue tree)
9393
(format t "~%")
94+
95+
;; Should print: 1 2 1 3 1 2 1
96+
(format t "[#]~%Recursive Inorder DFS for Binary Tree:~%")
97+
(dfs-recursive-inorder-btree binary-tree)
98+
(format t "~%")

‎contents/tree_traversal/code/coconut/tree_traversal.coco

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,42 +50,37 @@ def bfs_queue(node is Node):
5050
def create_tree(num_rows, num_child):
5151
"""Creates a simple tree, where every node has
5252
'num_child' children and is 'num_rows' deep."""
53-
if num_rows == 1:
54-
return Node(1, ())
53+
if num_rows == 0:
54+
return Node(0, ())
5555
else:
5656
return Node(num_rows, tuple(create_tree(num_rows-1, num_child)
5757
for _ in range(num_child)))
5858

5959

6060
if __name__ =='__main__':
6161
# A ternary tree for testing
62-
tree = create_tree(3, 3)
62+
tree = create_tree(2, 3)
6363

64-
# Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1
65-
print("Recursive DFS:")
64+
print("[#]\nRecursive DFS:")
6665
dfs_recursive(tree)
6766
print()
6867

69-
# Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3
70-
print("Recursive Postorder DFS:")
68+
print("[#]\nRecursive Postorder DFS:")
7169
dfs_recursive_postorder(tree)
7270
print()
7371

74-
# Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1
75-
print("Stack (DFS):")
72+
print("[#]\nStack-based DFS:")
7673
dfs_stack(tree)
7774
print()
7875

79-
# Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1
80-
print("Queue (BFS):")
76+
print("[#]\nQueue-based BFS:")
8177
bfs_queue(tree)
8278
print()
8379

8480
# And a binary tree for testing
8581
binary_tree = create_tree(3, 2)
8682

87-
# Should print: 1 2 1 3 1 2 1
88-
print("Recursive Inorder Binary Tree:")
83+
print("[#]\nRecursive Inorder DFS for Binary Tree:")
8984
dfs_recursive_inorder_btree(binary_tree)
9085
print()
9186

‎contents/tree_traversal/code/crystal/tree-traversal.cr

Lines changed: 12 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,26 @@ class Node
55
end
66

77
def dfs_recursive(node)
8-
print node.id
8+
print "#{node.id} "
99
node.children.each{ |child| dfs_recursive child }
1010
end
1111

1212
def dfs_recursive_postorder(node)
1313
node.children.each{ |child| dfs_recursive_postorder child }
14-
print node.id
14+
print "#{node.id} "
1515
end
1616

1717
def dfs_recursive_inorder_btree(node)
1818
case node.children.size
1919
when 2
2020
dfs_recursive_inorder_btree node.children[0]
21-
print node.id
21+
print "#{node.id} "
2222
dfs_recursive_inorder_btree node.children[1]
2323
when 1
2424
dfs_recursive_inorder_btree node.children[0]
25-
print node.id
25+
print "#{node.id} "
2626
when 0
27-
print node.id
27+
print "#{node.id} "
2828
else
2929
print "Not a binary tree!"
3030
end
@@ -35,7 +35,7 @@ def dfs_stack(node)
3535

3636
until stack.empty?
3737
temp = stack.pop
38-
print temp.id
38+
print "#{temp.id} "
3939
temp.children.each{ |child| stack.push child }
4040
end
4141
end
@@ -45,7 +45,7 @@ def bfs_queue(node)
4545

4646
until queue.empty?
4747
temp = queue.shift
48-
print temp.id
48+
print "#{temp.id} "
4949
temp.children.each{ |child| queue.push child }
5050
end
5151
end
@@ -60,54 +60,28 @@ def create_tree(levels, num_childs)
6060
Node.new(levels, children)
6161
end
6262

63-
def print_tree(node, depth = [] of String)
64-
puts "(#{node.id})"
65-
depth.push " "
66-
len = node.children.size - 1
67-
68-
(0 .. len).each do |i|
69-
depth.each{|c| print c}
70-
unless i == len
71-
print ""
72-
depth.push ""
73-
print_tree node.children[i], depth
74-
depth.pop
75-
else
76-
print ""
77-
depth.push " "
78-
print_tree node.children[i], depth
79-
depth.pop
80-
end
81-
end
82-
depth.pop
83-
end
84-
8563
def main
86-
puts "Creating Tree"
8764
root = create_tree levels: 2, num_childs: 3
88-
print_tree root
8965

90-
puts "Using recursive DFS:"
66+
puts "[#]\nRecursive DFS:"
9167
dfs_recursive root
9268
puts
9369

94-
puts "Using recursive DFS with post-order traversal:"
70+
puts "[#]\nRecursive Postorder DFS:"
9571
dfs_recursive_postorder root
9672
puts
9773

98-
puts "Using stack-based DFS:"
74+
puts "[#]\nStack-based DFS:"
9975
dfs_stack root
10076
puts
10177

102-
puts "Using queue-based BFS:"
78+
puts "[#]\nQueue-based BFS:"
10379
bfs_queue root
10480
puts
10581

106-
puts "Creating binary tree to test in-order traversal"
10782
root_bin = create_tree levels: 3, num_childs: 2
108-
print_tree root_bin
10983

110-
puts "Using In-order DFS:"
84+
puts "[#]\nRecursive Inorder DFS for Binary Tree:"
11185
dfs_recursive_inorder_btree root_bin
11286
puts
11387
end

‎contents/tree_traversal/code/csharp/Program.cs

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,27 @@ class Program
77
{
88
static void Main(string[] args)
99
{
10-
Console.WriteLine("TreeTraversal");
11-
var tree = new Tree(3, 3);
12-
Console.WriteLine("DFSRecursive:");
10+
var tree = new Tree(2, 3);
11+
Console.WriteLine("[#]\nRecursive DFS:");
1312
tree.DFSRecursive();
14-
Console.WriteLine("DFSStack:");
13+
Console.WriteLine();
14+
15+
Console.WriteLine("[#]\nRecursive Postorder DFS:");
16+
tree.DFSRecursivePostorder();
17+
Console.WriteLine();
18+
19+
Console.WriteLine("[#]\nStack-based DFS:");
1520
tree.DFSStack();
16-
Console.WriteLine("BFSQueue:");
21+
Console.WriteLine();
22+
23+
Console.WriteLine("[#]\nQueue-based BFS:");
1724
tree.BFSQueue();
18-
Console.WriteLine("DFSRecursivePostorder");
19-
tree.DFSRecursivePostorder();
25+
Console.WriteLine();
2026

21-
// Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work.
22-
// Console.WriteLine("DFSRecursiveInorder (fail)");
23-
// tree.DFSRecursiveInorderBinary();
2427
tree = new Tree(3, 2);
25-
Console.WriteLine("DFSRecursiveInorder (succeed)");
28+
Console.WriteLine("[#]\nRecursive Inorder DFS for Binary Tree:");
2629
tree.DFSRecursiveInorderBinary();
30+
Console.WriteLine();
2731
}
2832
}
2933
}

‎contents/tree_traversal/code/csharp/Tree.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ public class Tree
1111

1212
public Tree(int depthCount, int childrenCount)
1313
{
14-
this.Id = 1;
14+
this.Id = depthCount;
1515

16-
if (!(depthCount <= 1))
16+
if (depthCount > 0)
1717
{
1818
for (int i = 0; i < childrenCount; i++)
19-
this._children.Add(new Tree(this.Id * 10 + i + 1, depthCount - 1, childrenCount));
19+
this._children.Add(new Tree(depthCount - 1, childrenCount));
2020
}
2121
}
2222

@@ -37,7 +37,7 @@ public void DFSRecursive()
3737

3838
void DFSRecursive(Tree tree)
3939
{
40-
Console.WriteLine(tree.Id);
40+
Console.Write(tree.Id + " ");
4141

4242
foreach (var c in tree._children)
4343
DFSRecursive(c);
@@ -53,7 +53,7 @@ void DFSRecursivePostorder(Tree tree)
5353
foreach (var c in tree._children)
5454
DFSRecursivePostorder(c);
5555

56-
Console.WriteLine(tree.Id);
56+
Console.Write(tree.Id + " ");
5757
}
5858
}
5959

@@ -70,11 +70,11 @@ void DFSRecursiveInorderBinary(Tree tree)
7070
if (tree._children.Count > 0)
7171
{
7272
DFSRecursiveInorderBinary(tree._children[0]);
73-
Console.WriteLine(tree.Id);
73+
Console.Write(tree.Id + " ");
7474
DFSRecursiveInorderBinary(tree._children[1]);
7575
}
7676
else
77-
Console.WriteLine(tree.Id);
77+
Console.Write(tree.Id + " ");
7878
}
7979
}
8080

@@ -85,7 +85,7 @@ public void DFSStack()
8585

8686
while (stack.Count != 0)
8787
{
88-
Console.WriteLine(stack.Peek().Id);
88+
Console.Write(stack.Peek().Id + " ");
8989
var temp = stack.Pop();
9090

9191
foreach (var c in temp._children)
@@ -100,7 +100,7 @@ public void BFSQueue()
100100

101101
while (queue.Count != 0)
102102
{
103-
Console.WriteLine(queue.Peek().Id);
103+
Console.Write(queue.Peek().Id + " ");
104104
var temp = queue.Dequeue();
105105

106106
foreach (var c in temp._children)
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net5.0</TargetFramework>
6+
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
7+
</PropertyGroup>
8+
9+
</Project>

‎contents/tree_traversal/code/golang/treetraversal.go

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,30 @@ type node struct {
88
}
99

1010
func dfsRecursive(n *node) {
11-
fmt.Println(n.id)
11+
fmt.Printf("%d ", n.id)
1212
for _, child := range n.children {
1313
dfsRecursive(child)
1414
}
1515
}
1616

1717
func dfsRecursivePostorder(n *node) {
1818
for _, child := range n.children {
19-
dfsRecursive(child)
19+
dfsRecursivePostorder(child)
2020
}
21-
fmt.Println(n.id)
21+
fmt.Printf("%d ", n.id)
2222
}
2323

2424
func dfsRecursiveInorderBtree(n *node) {
2525
switch len(n.children) {
2626
case 2:
2727
dfsRecursiveInorderBtree(n.children[0])
28-
fmt.Println(n.id)
28+
fmt.Printf("%d ", n.id)
2929
dfsRecursiveInorderBtree(n.children[1])
3030
case 1:
3131
dfsRecursiveInorderBtree(n.children[0])
32-
fmt.Println(n.id)
32+
fmt.Printf("%d ", n.id)
3333
case 0:
34-
fmt.Println(n.id)
34+
fmt.Printf("%d ", n.id)
3535
default:
3636
fmt.Println("This is not a binary tree")
3737
}
@@ -43,7 +43,7 @@ func dfsStack(n *node) {
4343
for len(stack) > 0 {
4444
cur := stack[0]
4545
stack = stack[1:]
46-
fmt.Println(cur.id)
46+
fmt.Printf("%d ", cur.id)
4747
stack = append(cur.children, stack...)
4848
}
4949
}
@@ -54,7 +54,7 @@ func bfsQueue(n *node) {
5454
for len(queue) > 0 {
5555
cur := queue[0]
5656
queue = queue[1:]
57-
fmt.Println(cur.id)
57+
fmt.Printf("%d ", cur.id)
5858
queue = append(queue, cur.children...)
5959
}
6060
}
@@ -74,17 +74,27 @@ func createTree(numRow, numChild int) *node {
7474
}
7575

7676
func main() {
77-
root := createTree(3, 3)
77+
root := createTree(2, 3)
7878
binTree := createTree(3, 2)
7979

80-
fmt.Println("DFS recursive:")
80+
fmt.Println("[#]\nRecursive DFS:")
8181
dfsRecursive(root)
82-
fmt.Println("DFS post order recursive:")
82+
fmt.Println()
83+
84+
fmt.Println("[#]\nRecursive Postorder DFS:")
8385
dfsRecursivePostorder(root)
84-
fmt.Println("DFS inorder binary tree:")
85-
dfsRecursiveInorderBtree(binTree)
86-
fmt.Println("DFS stack:")
86+
fmt.Println()
87+
88+
fmt.Println("[#]\nStack-based DFS:")
8789
dfsStack(root)
88-
fmt.Println("BFS queue:")
90+
fmt.Println()
91+
92+
fmt.Println("[#]\nQueue-based BFS:")
8993
bfsQueue(root)
94+
fmt.Println()
95+
96+
fmt.Println("[#]\nRecursive Inorder DFS for Binary Tree:")
97+
dfsRecursiveInorderBtree(binTree)
98+
fmt.Println()
99+
90100
}
Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
data Tree a = Node
2-
{ node :: a
3-
, forest :: [Tree a]
4-
} deriving (Show)
2+
{ node :: a,
3+
forest :: [Tree a]
4+
}
5+
deriving (Show)
56

67
dfs :: Tree a -> [a]
78
dfs (Node x ts) = x : concatMap dfs ts
@@ -19,34 +20,30 @@ dfsStack :: Tree a -> [a]
1920
dfsStack t = go [t]
2021
where
2122
go [] = []
22-
go ((Node x ts):stack) = x : go (ts ++ stack)
23+
go ((Node x ts) : stack) = x : go (ts ++ stack)
2324

2425
bfs :: Tree a -> [a]
2526
bfs (Node x ts) = x : go ts
2627
where
2728
go [] = []
2829
go ts = map node ts ++ go (concatMap forest ts)
2930

30-
toBin :: Tree a -> Tree a
31-
toBin (Node x ts) = Node x (map toBin $ take 2 ts)
31+
createTree :: Int -> Int -> Tree Int
32+
createTree 0 _ = Node 0 []
33+
createTree numRow numChild = Node numRow children
34+
where
35+
children = map (createTree (numRow - 1)) $ replicate numChild numChild
3236

3337
main = do
34-
print $ dfs testTree
35-
print $ dfsPostOrder testTree
36-
print $ dfsInOrder $ toBin testTree
37-
print $ dfsStack testTree
38-
print $ bfs testTree
39-
40-
testTree :: Tree Int
41-
testTree =
42-
Node
43-
1
44-
[ Node 2 [Node 3 [], Node 4 [Node 5 []]]
45-
, Node
46-
6
47-
[ Node 7 []
48-
, Node 8 [Node 9 [Node 10 [Node 11 []], Node 12 []]]
49-
, Node 13 [Node 14 []]
50-
]
51-
, Node 15 []
52-
]
38+
let testTree = createTree 2 3
39+
showNodes = unwords . map show
40+
putStrLn "[#]\nRecursive DFS:"
41+
putStrLn $ showNodes $ dfs testTree
42+
putStrLn "[#]\nRecursive Postorder DFS:"
43+
putStrLn $ showNodes $ dfsPostOrder testTree
44+
putStrLn "[#]\nStack-based DFS:"
45+
putStrLn $ showNodes $ dfsStack testTree
46+
putStrLn "[#]\nQueue-based BFS:"
47+
putStrLn $ showNodes $ bfs testTree
48+
putStrLn "[#]\nRecursive Inorder DFS for Binary Tree:"
49+
putStrLn $ showNodes $ dfsInOrder $ createTree 3 2
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//submitted by xam4lor
2+
public class MainClass {
3+
public static void main(String[] args) {
4+
Tree tree = new Tree(2, 3);
5+
6+
System.out.println("[#]\nRecursive DFS:");
7+
tree.dfsRecursive();
8+
System.out.println();
9+
10+
System.out.println("[#]\nRecursive Postorder DFS:");
11+
tree.dfsRecursivePostOrder();
12+
System.out.println();
13+
14+
15+
System.out.println("[#]\nStack-based DFS:");
16+
tree.dfsStack();
17+
System.out.println();
18+
19+
20+
System.out.println("[#]\nQueue-based BFS:");
21+
tree.bfsQueue();
22+
System.out.println();
23+
24+
25+
// Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work.
26+
//System.out.println("Using in-order binary recursive DFS : (fail)");
27+
//tree.dfsRecursiveInOrderBinary();
28+
29+
tree = new Tree(3, 2);
30+
System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:");
31+
tree.dfsRecursiveInOrderBinary();
32+
System.out.println();
33+
}
34+
}

‎contents/tree_traversal/code/java/Tree.java

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import java.util.ArrayList;
2-
import java.util.PriorityQueue;
2+
import java.util.LinkedList;
33
import java.util.Queue;
44
import java.util.Stack;
55

@@ -8,8 +8,8 @@ public class Tree {
88

99
public Tree(int rowCount, int childrenCount) {
1010
// this.root is the root node of the Tree
11-
this.root = new Node(1);
12-
this.createAllChildren(this.root, rowCount, childrenCount);
11+
this.root = new Node(rowCount);
12+
this.createAllChildren(this.root, rowCount-1, childrenCount);
1313
}
1414

1515

@@ -18,7 +18,7 @@ public void dfsRecursive() {
1818
}
1919

2020
private void dfsRecursive(Node node) {
21-
System.out.println(node.id);
21+
System.out.print(node.id + " ");
2222

2323
for (Node n : node.children) {
2424
dfsRecursive(n);
@@ -36,7 +36,7 @@ private void dfsRecursivePostOrder(Node node) {
3636
}
3737

3838
// Here we are doing something ...
39-
System.out.println(node.id);
39+
System.out.print(node.id + " ");
4040
}
4141

4242

@@ -48,15 +48,15 @@ private void dfsRecursiveInOrderBinary(Node node) {
4848
switch (node.children.size()) {
4949
case 2:
5050
dfsRecursiveInOrderBinary(node.children.get(0));
51-
System.out.println(node.id);
51+
System.out.print(node.id + " ");
5252
dfsRecursiveInOrderBinary(node.children.get(1));
5353
break;
5454
case 1:
5555
dfsRecursiveInOrderBinary(node.children.get(0));
56-
System.out.println(node.id);
56+
System.out.print(node.id + " ");
5757
break;
5858
case 0:
59-
System.out.println(node.id);
59+
System.out.print(node.id + " ");
6060
break;
6161
default:
6262
System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!");
@@ -71,7 +71,7 @@ public void dfsStack() {
7171
Node tmp;
7272

7373
while (stack.size() != 0) {
74-
System.out.println(stack.peek().id);
74+
System.out.print(stack.peek().id + " ");
7575
tmp = stack.pop();
7676

7777
for (Node c : tmp.children) {
@@ -81,11 +81,11 @@ public void dfsStack() {
8181
}
8282

8383
public void bfsQueue() {
84-
Queue<Node> queue = new PriorityQueue<Node>();
84+
Queue<Node> queue = new LinkedList<Node>();
8585
queue.add(this.root);
8686

8787
while (queue.size() != 0) {
88-
System.out.println(queue.peek().id);
88+
System.out.print(queue.peek().id + " ");
8989
Node temp = queue.poll(); // return null if the queue is empty
9090

9191
if (temp != null) {
@@ -98,12 +98,12 @@ public void bfsQueue() {
9898

9999

100100
private void createAllChildren(Node node, int rowCount, int childrenCount) {
101-
if (rowCount <= 1) {
101+
if (rowCount < 0) {
102102
return;
103103
}
104104

105105
for (int i = 0; i < childrenCount; i++) {
106-
node.children.add(new Node(node.id * 10 + i + 1));
106+
node.children.add(new Node(rowCount));
107107
createAllChildren(node.children.get(i), rowCount - 1, childrenCount);
108108
}
109109
}
@@ -128,32 +128,34 @@ public int compareTo(Node other) {
128128
}
129129

130130
public static void main(String[] args) {
131-
System.out.println("Creating Tree");
132-
Tree tree = new Tree(3, 3);
131+
Tree tree = new Tree(2, 3);
133132

134-
System.out.println("Using recursive DFS :");
133+
System.out.println("[#]\nRecursive DFS:");
135134
tree.dfsRecursive();
135+
System.out.println();
136136

137-
System.out.println("Using stack-based DFS :");
137+
System.out.println("[#]\nRecursive Postorder DFS:");
138+
tree.dfsRecursivePostOrder();
139+
System.out.println();
140+
141+
142+
System.out.println("[#]\nStack-based DFS:");
138143
tree.dfsStack();
144+
System.out.println();
139145

140-
System.out.println("Using queue-based BFS :");
141-
tree.bfsQueue();
142146

143-
System.out.println("Using post-order recursive DFS :");
144-
tree.dfsRecursivePostOrder();
147+
System.out.println("[#]\nQueue-based BFS:");
148+
tree.bfsQueue();
149+
System.out.println();
145150

146151

147152
// Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work.
148-
System.out.println("Using in-order binary recursive DFS : (fail)");
149-
tree.dfsRecursiveInOrderBinary();
153+
//System.out.println("Using in-order binary recursive DFS : (fail)");
154+
//tree.dfsRecursiveInOrderBinary();
150155

151156
tree = new Tree(3, 2);
152-
System.out.println("Using in-order binary recursive DFS : (succeed)");
157+
System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:");
153158
tree.dfsRecursiveInOrderBinary();
154-
155-
156-
System.out.println("");
159+
System.out.println();
157160
}
158-
159161
}

‎contents/tree_traversal/code/javascript/tree.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ function dfsPreorder(tree) {
1414
return;
1515
}
1616

17-
console.log(tree.id);
17+
process.stdout.write(tree.id + " ");
1818
tree.children.forEach(dfsPreorder);
1919
}
2020

@@ -24,7 +24,7 @@ function dfsPostorder(tree) {
2424
}
2525

2626
tree.children.forEach(dfsPostorder);
27-
console.log(tree.id);
27+
process.stdout.write(tree.id + " ");
2828
}
2929

3030
function dfsInorder(tree) {
@@ -54,7 +54,7 @@ function dfsIterative(tree) {
5454
const stack = [tree];
5555
while (stack.length > 0) {
5656
const current = stack.pop();
57-
console.log(current.id);
57+
process.stdout.write(current.id + " ");
5858
stack.push(...current.children);
5959
}
6060
}
@@ -63,13 +63,26 @@ function bfs(tree) {
6363
const queue = [tree];
6464
while (queue.length > 0) {
6565
const current = queue.shift();
66-
console.log(current.id);
66+
process.stdout.write(current.id + " ");
6767
queue.push(...current.children);
6868
}
6969
}
7070

71-
const root = createTree(3, 3);
71+
const root = createTree(2, 3);
72+
console.log("[#]\nRecursive DFS:");
7273
dfsPreorder(root);
74+
console.log();
75+
console.log("[#]\nRecursive Postorder DFS:");
7376
dfsPostorder(root);
77+
console.log();
78+
console.log("[#]\nStack-based DFS:");
7479
dfsIterative(root);
80+
console.log();
81+
console.log("[#]\nQueue-based BFS:");
7582
bfs(root);
83+
console.log();
84+
const root_binary = createTree(3, 2);
85+
console.log("[#]\nRecursive Inorder DFS for Binary Tree:");
86+
dfsInorder(root_binary);
87+
console.log();
88+

‎contents/tree_traversal/code/julia/Tree.jl

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using DataStructures
1+
using DataStructures, Printf
22

33
struct Node
44
children::Vector{Node}
@@ -8,7 +8,7 @@ end
88

99
function DFS_recursive(n::Node)
1010
# Here we are doing something...
11-
println(n.ID)
11+
print(n.ID, " ")
1212

1313
for child in n.children
1414
DFS_recursive(child)
@@ -22,21 +22,21 @@ function DFS_recursive_postorder(n::Node)
2222
end
2323

2424
# Here we are doing something...
25-
println(n.ID)
25+
print(n.ID, " ")
2626
end
2727

2828
# This assumes only 2 children, but accounts for other possibilities
2929
function DFS_recursive_inorder_btree(n::Node)
3030

3131
if (length(n.children) == 2)
3232
DFS_recursive_inorder_btree(n.children[1])
33-
println(n.ID)
33+
print(n.ID, " ")
3434
DFS_recursive_inorder_btree(n.children[2])
3535
elseif (length(n.children) == 1)
3636
DFS_recursive_inorder_btree(n.children[1])
37-
println(n.ID)
37+
print(n.ID, " ")
3838
elseif (length(n.children) == 0)
39-
println(n.ID)
39+
print(n.ID, " ")
4040
else
4141
println("Not a binary tree!")
4242
end
@@ -47,7 +47,7 @@ function DFS_stack(n::Node)
4747
push!(s, n)
4848

4949
while(length(s) > 0)
50-
println(first(s).ID)
50+
print(top(s).ID, " ")
5151
temp = pop!(s)
5252
for child in temp.children
5353
push!(s, child)
@@ -60,7 +60,7 @@ function BFS_queue(n::Node)
6060
enqueue!(q, n)
6161

6262
while(length(q) > 0)
63-
println(first(q).ID)
63+
print(first(q).ID, " ")
6464
temp = dequeue!(q)
6565
for child in temp.children
6666
enqueue!(q, child)
@@ -84,26 +84,28 @@ function create_tree(num_row::Int64, num_child::Int64)
8484
end
8585

8686
function main()
87-
88-
println("Creating Tree")
8987
root = create_tree(2, 3)
9088

91-
println("Using recursive DFS:")
89+
println("[#]\nRecursive DFS:")
9290
DFS_recursive(root);
91+
println()
9392

94-
println("Using recursive DFS with post-order traversal:")
93+
println("[#]\nRecursive Postorder DFS:")
9594
DFS_recursive_postorder(root);
95+
println()
9696

97-
println("Using stack-based DFS:")
97+
println("[#]\nStack-based DFS:")
9898
DFS_stack(root);
99+
println()
99100

100-
println("Using queue-based BFS:")
101+
println("[#]\nQueue-based BFS:")
101102
BFS_queue(root);
103+
println()
102104

103-
println("Creating binary tree to test in-order traversal.")
104105
root_binary = create_tree(3,2)
105-
println("Using In-order DFS:")
106+
println("[#]\nRecursive Inorder DFS for Binary Tree:")
106107
DFS_recursive_inorder_btree(root_binary)
108+
println()
107109
end
108110

109111
main()

‎contents/tree_traversal/code/php/tree_traversal.php

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@ class TreeTraversal
4040
{
4141
public static function DFSRecursive(Tree $tree): void
4242
{
43-
if ($tree->getId()) {
44-
echo $tree->getId() . PHP_EOL;
45-
}
43+
echo $tree->getId() . ' ';
4644
foreach ($tree->getChildren() as $child) {
4745
static::DFSRecursive($child);
4846
}
@@ -53,23 +51,23 @@ public static function DFSRecursivePostorder(Tree $tree): void
5351
foreach ($tree->getChildren() as $child) {
5452
static::DFSRecursivePostorder($child);
5553
}
56-
echo $tree->getId() . PHP_EOL;
54+
echo $tree->getId() . ' ';
5755
}
5856

5957
public static function DFSRecursiveInorderBinary(Tree $tree): void
6058
{
6159
switch (count($tree->getChildren())) {
6260
case 2:
6361
static::DFSRecursiveInorderBinary($tree->getChildren()[0]);
64-
echo $tree->getId() . PHP_EOL;
62+
echo $tree->getId() . ' ';
6563
static::DFSRecursiveInorderBinary($tree->getChildren()[1]);
6664
break;
6765
case 1:
6866
static::DFSRecursiveInorderBinary($tree->getChildren()[0]);
69-
echo $tree->getId() . PHP_EOL;
67+
echo $tree->getId() . ' ';
7068
break;
7169
case 0:
72-
echo $tree->getId() . PHP_EOL;
70+
echo $tree->getId() . ' ';
7371
break;
7472
default:
7573
throw new InvalidArgumentException('Not a binary tree!');
@@ -83,7 +81,7 @@ public static function DFSStack(Tree $tree): void
8381
$temp = null;
8482

8583
while (null !== ($temp = array_pop($stack))) {
86-
echo $temp->getId() . PHP_EOL;
84+
echo $temp->getId() . ' ';
8785
foreach ($temp->getChildren() as $child) {
8886
$stack[] = $child;
8987
}
@@ -96,48 +94,50 @@ public static function DFSQueue(Tree $tree): void
9694
$temp = null;
9795

9896
while (null !== ($temp = array_shift($stack))) {
99-
echo $temp->getId() . PHP_EOL;
97+
echo $temp->getId() . ' ';
10098
foreach ($temp->getChildren() as $child) {
10199
$stack[] = $child;
102100
}
103101
}
104102
}
105103
}
106104

107-
function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree
105+
function generate_tree(int $numOfRows, int $numOfChildren): Tree
108106
{
109-
if ($id === -1) {
110-
$id = 1;
111-
}
112-
$node = new Tree($id);
107+
$node = new Tree($numOfRows);
113108

114-
if ($numOfRows > 1) {
109+
if ($numOfRows > 0) {
115110
for ($i = 0; $i < $numOfChildren; $i++) {
116-
$child = generate_tree($numOfRows - 1, $numOfChildren, $id * 10 + $i + 1);
111+
$child = generate_tree($numOfRows - 1, $numOfChildren);
117112
$node->addChild($child);
118113
}
119114
}
120115

121116
return $node;
122117
}
123118

124-
$node = generate_tree(3, 3);
119+
$node = generate_tree(2, 3);
125120

126-
echo 'DFS Recursive:' . PHP_EOL;
121+
echo '[#]' . PHP_EOL . 'Recursive DFS:' . PHP_EOL;
127122
TreeTraversal::DFSRecursive($node);
123+
echo PHP_EOL;
128124

129-
echo 'DFS Recursive Postorder:' . PHP_EOL;
125+
echo '[#]' . PHP_EOL . 'Recursive Postorder DFS:' . PHP_EOL;
130126
TreeTraversal::DFSRecursivePostorder($node);
127+
echo PHP_EOL;
131128

132-
echo 'DFS Stack:' . PHP_EOL;
129+
echo '[#]' . PHP_EOL . 'Stack-based DFS:' . PHP_EOL;
133130
TreeTraversal::DFSStack($node);
131+
echo PHP_EOL;
134132

135-
echo 'DFS Queue:' . PHP_EOL;
133+
echo '[#]' . PHP_EOL . 'Queue-based BFS:' . PHP_EOL;
136134
TreeTraversal::DFSQueue($node);
135+
echo PHP_EOL;
137136

138137
// If you want to try to run binary order on a non-binary tree,
139138
// comment out the generation of the new tree below.
140139
// If you do that, an exception will be thrown
141140
$node = generate_tree(3, 2);
142-
echo 'DFS Recursive Inorder Binary:' . PHP_EOL;
141+
echo '[#]' . PHP_EOL . 'Recursive Inorder DFS for Binary Tree:' . PHP_EOL;
143142
TreeTraversal::DFSRecursiveInorderBinary($node);
143+
echo PHP_EOL;

‎contents/tree_traversal/code/python/Tree_example.py

Lines changed: 0 additions & 99 deletions
This file was deleted.
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
class Node:
2+
def __init__(self):
3+
self.data = None
4+
self.children = []
5+
6+
def create_tree(node, num_row, num_child):
7+
node.data = num_row
8+
9+
if num_row > 0:
10+
for i in range(num_child):
11+
child = create_tree(Node(), num_row-1, num_child)
12+
node.children.append(child)
13+
14+
return node
15+
16+
17+
def dfs_recursive(node):
18+
if node.data != None:
19+
print(node.data, end=' ')
20+
21+
for child in node.children:
22+
dfs_recursive(child)
23+
24+
25+
def dfs_recursive_postorder(node):
26+
for child in node.children:
27+
dfs_recursive_postorder(child)
28+
29+
if node.data != None:
30+
print(node.data, end=' ')
31+
32+
33+
# This assumes only 2 children, but accounts for other possibilities
34+
def dfs_recursive_inorder_btree(node):
35+
if len(node.children) == 2:
36+
dfs_recursive_inorder_btree(node.children[0])
37+
print(node.data, end=' ')
38+
dfs_recursive_inorder_btree(node.children[1])
39+
elif len(node.children) == 1:
40+
dfs_recursive_inorder_btree(node.children[0])
41+
print(node.data, end=' ')
42+
elif len(node.children) == 0:
43+
print(node.data, end=' ')
44+
else:
45+
print("Not a binary tree!")
46+
47+
48+
def dfs_stack(node):
49+
stack = []
50+
stack.append(node)
51+
52+
temp = None
53+
54+
while len(stack) > 0:
55+
print(stack[-1].data, end=' ')
56+
temp = stack.pop()
57+
58+
for child in temp.children:
59+
stack.append(child)
60+
61+
62+
def bfs_queue(node):
63+
queue = []
64+
queue.append(node)
65+
66+
temp = None
67+
68+
while len(queue) > 0:
69+
print(queue[0].data, end=' ')
70+
temp = queue.pop(0)
71+
72+
for child in temp.children:
73+
queue.append(child)
74+
75+
76+
def main():
77+
tree = create_tree(Node(), 2, 3)
78+
79+
print("[#]\nRecursive DFS:")
80+
dfs_recursive(tree)
81+
print()
82+
83+
print("[#]\nRecursive Postorder DFS:")
84+
dfs_recursive_postorder(tree)
85+
print()
86+
87+
print("[#]\nStack-based DFS:")
88+
dfs_stack(tree)
89+
print()
90+
91+
print("[#]\nQueue-based BFS:")
92+
bfs_queue(tree)
93+
print()
94+
95+
binary_tree = create_tree(Node(), 3, 2)
96+
97+
print("[#]\nRecursive Inorder DFS for Binary Tree:")
98+
dfs_recursive_inorder_btree(binary_tree)
99+
print()
100+
101+
if __name__ == '__main__':
102+
main()
103+

‎contents/tree_traversal/code/rust/tree.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ struct Node {
77
}
88

99
fn dfs_recursive(n: &Node) {
10-
println!("{}", n.value);
10+
print!("{} ", n.value);
1111

1212
for child in &n.children {
1313
dfs_recursive(child);
@@ -19,30 +19,30 @@ fn dfs_recursive_postorder(n: &Node) {
1919
dfs_recursive_postorder(child);
2020
}
2121

22-
println!("{}", n.value);
22+
print!("{} ", n.value);
2323
}
2424

2525
fn dfs_recursive_inorder_btree(n: &Node) {
2626
match &n.children[..] {
2727
[left, right] => {
2828
dfs_recursive_inorder_btree(left);
29-
println!("{}", n.value);
29+
print!("{} ", n.value);
3030
dfs_recursive_inorder_btree(right);
3131
}
3232
[left] => {
3333
dfs_recursive_inorder_btree(left);
34-
println!("{}", n.value);
34+
print!("{} ", n.value);
3535
}
36-
[] => println!("{}", n.value),
37-
_ => println!("This is not a binary tree."),
36+
[] => print!("{} ", n.value),
37+
_ => print!("This is not a binary tree. "),
3838
}
3939
}
4040

4141
fn dfs_stack(n: &Node) {
4242
let mut stack = vec![n];
4343

4444
while let Some(current) = stack.pop() {
45-
println!("{}", current.value);
45+
print!("{} ", current.value);
4646
stack.extend(&current.children);
4747
}
4848
}
@@ -52,7 +52,7 @@ fn bfs_queue(n: &Node) {
5252
queue.push_back(n);
5353

5454
while let Some(current) = queue.pop_front() {
55-
println!("{}", current.value);
55+
print!("{} ", current.value);
5656
queue.extend(&current.children);
5757
}
5858
}
@@ -78,19 +78,24 @@ fn create_tree(num_row: u64, num_child: u64) -> Node {
7878
fn main() {
7979
let root = create_tree(2, 3);
8080

81-
println!("Recursive DFS:");
81+
println!("[#]\nRecursive DFS:");
8282
dfs_recursive(&root);
83+
println!();
8384

84-
println!("Stack DFS:");
85+
println!("[#]\nRecursive Postorder DFS:");
86+
dfs_recursive_postorder(&root);
87+
println!();
88+
89+
println!("[#]\nStack-based DFS:");
8590
dfs_stack(&root);
91+
println!();
8692

87-
println!("Queue BFS:");
93+
println!("[#]\nQueue-based BFS:");
8894
bfs_queue(&root);
95+
println!();
8996

90-
println!("Recursive post-order DFS:");
91-
dfs_recursive_postorder(&root);
92-
93-
println!("Recursive in-order DFS BTree:");
97+
println!("[#]\nRecursive Inorder DFS for Binary Tree:");
9498
let root_binary = create_tree(3, 2);
9599
dfs_recursive_inorder_btree(&root_binary);
100+
println!();
96101
}

‎contents/tree_traversal/code/swift/tree.swift

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ func createTree(numRows: Int, numChildren: Int) -> Node {
2222
}
2323

2424
func dfsRecursive(node: Node) {
25-
print(node.value)
25+
print(node.value, terminator:" ")
2626

2727
for child in node.children! {
2828
dfsRecursive(node: child)
@@ -34,19 +34,19 @@ func dfsRecursivePostOrder(node: Node) {
3434
dfsRecursivePostOrder(node: child)
3535
}
3636

37-
print(node.value)
37+
print(node.value, terminator:" ")
3838
}
3939

4040
func dfsRecursiveInOrderBinary(node: Node) {
4141
if node.children?.count == 2 {
4242
dfsRecursiveInOrderBinary(node: node.children![0])
43-
print(node.value)
43+
print(node.value, terminator:" ")
4444
dfsRecursiveInOrderBinary(node: node.children![1])
4545
} else if node.children?.count == 1 {
4646
dfsRecursiveInOrderBinary(node: node.children![0])
47-
print(node.value)
47+
print(node.value, terminator:" ")
4848
} else if node.children?.count == 0 {
49-
print(node.value)
49+
print(node.value, terminator:" ")
5050
} else {
5151
print("Not a binary tree!")
5252
}
@@ -58,7 +58,7 @@ func dfsStack(node: Node) {
5858

5959
while stack.count > 0 {
6060
temp = stack.popLast()!
61-
print(temp.value)
61+
print(temp.value, terminator:" ")
6262

6363
for child in temp.children! {
6464
stack.append(child)
@@ -72,7 +72,7 @@ func bfsQueue(node: Node) {
7272

7373
while queue.count > 0 {
7474
temp = queue.remove(at: 0)
75-
print(temp.value)
75+
print(temp.value, terminator:" ")
7676

7777
for child in temp.children! {
7878
queue.append(child)
@@ -81,24 +81,29 @@ func bfsQueue(node: Node) {
8181
}
8282

8383
func main() {
84-
let root = createTree(numRows: 3, numChildren: 3)
84+
let root = createTree(numRows: 2, numChildren: 3)
8585

86-
print("Using recursive DFS:")
86+
print("[#]\nRecursive DFS:")
8787
dfsRecursive(node: root)
88+
print()
8889

89-
print("Using recursive postorder DFS:")
90+
print("[#]\nRecursive Postorder DFS:")
9091
dfsRecursivePostOrder(node: root)
92+
print()
9193

92-
print("Using stack-based DFS:")
94+
print("[#]\nStack-based DFS:")
9395
dfsStack(node: root)
96+
print()
9497

95-
print("Using queue-based BFS:")
98+
print("[#]\nQueue-based BFS:")
9699
bfsQueue(node: root)
100+
print()
97101

98102
let rootBinary = createTree(numRows: 3, numChildren: 2)
99103

100-
print("Using In-order DFS:")
104+
print("[#]\nRecursive Inorder DFS for Binary Tree:")
101105
dfsRecursiveInOrderBinary(node: rootBinary)
106+
print()
102107
}
103108

104109
main()

‎contents/tree_traversal/tree_traversal.md

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Trees are naturally recursive data structures, and because of this, we cannot ac
1717
[import:1-10, lang:"javascript"](code/javascript/tree.js)
1818
As a note, a `node` struct is not necessary in javascript, so this is an example of how a tree might be constructed.
1919
{% sample lang="py" %}
20-
[import:1-4, lang:"python"](code/python/Tree_example.py)
20+
[import:1-4, lang:"python"](code/python/tree_traversal.py)
2121
{% sample lang="scratch" %}
2222
<p>
2323
<img class="center" src="code/scratch/struct.svg" style="width:25%" />
@@ -64,19 +64,19 @@ Because of this, the most straightforward way to traverse the tree might be recu
6464
{% sample lang="js" %}
6565
[import:12-19, lang:"javascript"](code/javascript/tree.js)
6666
{% sample lang="py" %}
67-
[import:18-23, lang:"python"](code/python/Tree_example.py)
67+
[import:17-22, lang:"python"](code/python/tree_traversal.py)
6868
{% sample lang="scratch" %}
6969
<p>
7070
<img class="center" src="code/scratch/dfs-pre.svg" style="width:40%" />
7171
</p>
7272
{% sample lang="rs" %}
7373
[import:9-15 lang:"rust"](code/rust/tree.rs)
7474
{% sample lang="hs" %}
75-
[import:6-7, lang:"haskell"](code/haskell/TreeTraversal.hs)
75+
[import:7-8, lang:"haskell"](code/haskell/TreeTraversal.hs)
7676
{% sample lang="swift" %}
7777
[import:24-30, lang:"swift"](code/swift/tree.swift)
7878
{% sample lang="php" %}
79-
[import:41-49, lang:"php"](code/php/tree_traversal.php)
79+
[import:41-47, lang:"php"](code/php/tree_traversal.php)
8080
{% sample lang="crystal" %}
8181
[import:7-10, lang:"crystal"](code/crystal/tree-traversal.cr)
8282
{% sample lang="st" %}
@@ -120,19 +120,19 @@ Now, in this case the first element searched through is still the root of the tr
120120
{% sample lang="js" %}
121121
[import:21-28, lang:"javascript"](code/javascript/tree.js)
122122
{% sample lang="py" %}
123-
[import:26-31, lang:"python"](code/python/Tree_example.py)
123+
[import:25-30, lang:"python"](code/python/tree_traversal.py)
124124
{% sample lang="scratch" %}
125125
<p>
126126
<img class="center" src="code/scratch/dfs-post.svg" style="width:40%" />
127127
</p>
128128
{% sample lang="rs" %}
129129
[import:17-24, lang:"rust"](code/rust/tree.rs)
130130
{% sample lang="hs" %}
131-
[import:9-10, lang:"haskell"](code/haskell/TreeTraversal.hs)
131+
[import:10-11, lang:"haskell"](code/haskell/TreeTraversal.hs)
132132
{% sample lang="swift" %}
133133
[import:32-38, lang:"swift"](code/swift/tree.swift)
134134
{% sample lang="php" %}
135-
[import:51-57, lang:"php"](code/php/tree_traversal.php)
135+
[import:49-55, lang:"php"](code/php/tree_traversal.php)
136136
{% sample lang="crystal" %}
137137
[import:12-15, lang:"crystal"](code/crystal/tree-traversal.cr)
138138
{% sample lang="st" %}
@@ -148,7 +148,7 @@ Now, in this case the first element searched through is still the root of the tr
148148
{% sample lang="m" %}
149149
[import:47-62, lang:"matlab"](code/matlab/tree.m)
150150
{% sample lang="coco" %}
151-
[import:11-15, lang:="coconut"](codo/coconut/tree_traversal.coco)
151+
[import:11-15, lang:="coconut"](code/coconut/tree_traversal.coco)
152152
{% endmethod %}
153153

154154
<p>
@@ -171,19 +171,19 @@ In this case, the first node visited is at the bottom of the tree and moves up t
171171
{% sample lang="js" %}
172172
[import:30-51, lang:"javascript"](code/javascript/tree.js)
173173
{% sample lang="py" %}
174-
[import:34-46, lang:"python"](code/python/Tree_example.py)
174+
[import:34-45, lang:"python"](code/python/tree_traversal.py)
175175
{% sample lang="scratch" %}
176176
<p>
177177
<img class="center" src="code/scratch/dfs-in.svg" style="width:40%" />
178178
</p>
179179
{% sample lang="rs" %}
180180
[import:25-40, lang:"rust"](code/rust/tree.rs)
181181
{% sample lang="hs" %}
182-
[import:12-16, lang:"haskell"](code/haskell/TreeTraversal.hs)
182+
[import:13-17, lang:"haskell"](code/haskell/TreeTraversal.hs)
183183
{% sample lang="swift" %}
184184
[import:40-53, lang:"swift"](code/swift/tree.swift)
185185
{% sample lang="php" %}
186-
[import:59-78, lang:"php"](code/php/tree_traversal.php)
186+
[import:57-76, lang:"php"](code/php/tree_traversal.php)
187187
{% sample lang="crystal" %}
188188
[import:17-31, lang:"crystal"](code/crystal/tree-traversal.cr)
189189
{% sample lang="st" %}
@@ -231,19 +231,19 @@ In code, it looks like this:
231231
{% sample lang="js" %}
232232
[import:53-60, lang:"javascript"](code/javascript/tree.js)
233233
{% sample lang="py" %}
234-
[import:49-60, lang:"python"](code/python/Tree_example.py)
234+
[import:48-59, lang:"python"](code/python/tree_traversal.py)
235235
{% sample lang="scratch" %}
236236
<p>
237237
<img class="center" src="code/scratch/dfs-stack.svg" style="width:70%" />
238238
</p>
239239
{% sample lang="rs" %}
240240
[import:41-48, lang:"rust"](code/rust/tree.rs)
241241
{% sample lang="hs" %}
242-
[import:18-22, lang:"haskell"](code/haskell/TreeTraversal.hs)
242+
[import:19-23, lang:"haskell"](code/haskell/TreeTraversal.hs)
243243
{% sample lang="swift" %}
244244
[import:55-67, lang:"swift"](code/swift/tree.swift)
245245
{% sample lang="php" %}
246-
[import:80-91, lang:"php"](code/php/tree_traversal.php)
246+
[import:78-89, lang:"php"](code/php/tree_traversal.php)
247247
{% sample lang="crystal" %}
248248
[import:33-41, lang:"crystal"](code/crystal/tree-traversal.cr)
249249
{% sample lang="st" %}
@@ -284,19 +284,19 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
284284
{% sample lang="js" %}
285285
[import:62-69, lang:"javascript"](code/javascript/tree.js)
286286
{% sample lang="py" %}
287-
[import:63-75, lang:"python"](code/python/Tree_example.py)
287+
[import:62-72, lang:"python"](code/python/tree_traversal.py)
288288
{% sample lang="scratch" %}
289289
<p>
290290
<img class="center" src="code/scratch/bfs.svg" style="width:70%" />
291291
</p>
292292
{% sample lang="rs" %}
293293
[import:50-58, lang:"rust"](code/rust/tree.rs)
294294
{% sample lang="hs" %}
295-
[import:24-28, lang:"haskell"](code/haskell/TreeTraversal.hs)
295+
[import:25-29, lang:"haskell"](code/haskell/TreeTraversal.hs)
296296
{% sample lang="swift" %}
297297
[import:69-81, lang:"swift"](code/swift/tree.swift)
298298
{% sample lang="php" %}
299-
[import:93-104, lang:"php"](code/php/tree_traversal.php)
299+
[import:91-102, lang:"php"](code/php/tree_traversal.php)
300300
{% sample lang="crystal" %}
301301
[import:43-51, lang:"crystal"](code/crystal/tree-traversal.cr)
302302
{% sample lang="st" %}
@@ -345,7 +345,7 @@ Here is a video describing tree traversal:
345345
{% sample lang="js" %}
346346
[import, lang:"javascript"](code/javascript/tree.js)
347347
{% sample lang="py" %}
348-
[import, lang:"python"](code/python/Tree_example.py)
348+
[import, lang:"python"](code/python/tree_traversal.py)
349349
{% sample lang="scratch" %}
350350

351351
The code snippets were taken from this [Scratch project](https://scratch.mit.edu/projects/174017753/)

0 commit comments

Comments
 (0)
Please sign in to comment.