Skip to content

Commit 44449b1

Browse files
committed
updated dfsInorder
1 parent 65599ee commit 44449b1

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

contents/tree_traversal/code/javascript/tree.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,17 +20,22 @@ function dfsPostorder(tree) {
2020
}
2121

2222
function dfsInorder(tree) {
23-
if (!tree) {
24-
return;
23+
switch (tree.children.length) {
24+
case 2:
25+
dfsInorder(tree.children[0]);
26+
console.log(tree.id);
27+
dfsInorder(tree.children[1]);
28+
break;
29+
case 1:
30+
dfsInorder(tree.children[0]);
31+
console.log(tree.id);
32+
break;
33+
case 0:
34+
console.log(tree.id);
35+
break;
36+
default:
37+
throw new Error("Postorder traversal is only valid for binary trees");
2538
}
26-
27-
if (tree.children.length > 2) {
28-
throw new Error("Postorder traversal is only valid for binary trees");
29-
}
30-
31-
dfsInorder(tree.children[0]);
32-
console.log(tree.id);
33-
dfsInorder(tree.children[1]);
3439
}
3540

3641
function dfsIterative(tree) {

contents/tree_traversal/tree_traversal.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t
163163
{% sample lang="java" %}
164164
[import:48-62, lang:"java"](code/java/Tree.java)
165165
{% sample lang="js" %}
166-
[import:22-34, lang:"javascript"](code/javascript/tree.js)
166+
[import:22-39, lang:"javascript"](code/javascript/tree.js)
167167
{% sample lang="py" %}
168168
[import:34-46, lang:"python"](code/python/Tree_example.py)
169169
{% sample lang="scratch" %}
@@ -221,7 +221,7 @@ In code, it looks like this:
221221
{% sample lang="java" %}
222222
[import:65-79, lang:"java"](code/java/Tree.java)
223223
{% sample lang="js" %}
224-
[import:36-43, lang:"javascript"](code/javascript/tree.js)
224+
[import:41-48, lang:"javascript"](code/javascript/tree.js)
225225
{% sample lang="py" %}
226226
[import:49-60, lang:"python"](code/python/Tree_example.py)
227227
{% sample lang="scratch" %}
@@ -272,7 +272,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
272272
{% sample lang="java" %}
273273
[import:81-95, lang:"java"](code/java/Tree.java)
274274
{% sample lang="js" %}
275-
[import:45-52, lang:"javascript"](code/javascript/tree.js)
275+
[import:50-57, lang:"javascript"](code/javascript/tree.js)
276276
{% sample lang="py" %}
277277
[import:63-75, lang:"python"](code/python/Tree_example.py)
278278
{% sample lang="scratch" %}

0 commit comments

Comments
 (0)