Skip to content

JavaScript tree traversal: updated dfsInorder #902

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 23, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions contents/tree_traversal/code/javascript/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,22 @@ function dfsPostorder(tree) {
}

function dfsInorder(tree) {
if (!tree) {
return;
switch (tree.children.length) {
case 2:
dfsInorder(tree.children[0]);
console.log(tree.id);
dfsInorder(tree.children[1]);
break;
case 1:
dfsInorder(tree.children[0]);
console.log(tree.id);
break;
case 0:
console.log(tree.id);
break;
default:
throw new Error("Postorder traversal is only valid for binary trees");
}

if (tree.children.length > 2) {
throw new Error("Postorder traversal is only valid for binary trees");
}

dfsInorder(tree.children[0]);
console.log(tree.id);
dfsInorder(tree.children[1]);
}

function dfsIterative(tree) {
Expand Down
6 changes: 3 additions & 3 deletions contents/tree_traversal/tree_traversal.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t
{% sample lang="java" %}
[import:48-62, lang:"java"](code/java/Tree.java)
{% sample lang="js" %}
[import:22-34, lang:"javascript"](code/javascript/tree.js)
[import:22-39, lang:"javascript"](code/javascript/tree.js)
{% sample lang="py" %}
[import:34-46, lang:"python"](code/python/Tree_example.py)
{% sample lang="scratch" %}
Expand Down Expand Up @@ -221,7 +221,7 @@ In code, it looks like this:
{% sample lang="java" %}
[import:65-79, lang:"java"](code/java/Tree.java)
{% sample lang="js" %}
[import:36-43, lang:"javascript"](code/javascript/tree.js)
[import:41-48, lang:"javascript"](code/javascript/tree.js)
{% sample lang="py" %}
[import:49-60, lang:"python"](code/python/Tree_example.py)
{% sample lang="scratch" %}
Expand Down Expand Up @@ -272,7 +272,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
{% sample lang="java" %}
[import:81-95, lang:"java"](code/java/Tree.java)
{% sample lang="js" %}
[import:45-52, lang:"javascript"](code/javascript/tree.js)
[import:50-57, lang:"javascript"](code/javascript/tree.js)
{% sample lang="py" %}
[import:63-75, lang:"python"](code/python/Tree_example.py)
{% sample lang="scratch" %}
Expand Down