Skip to content

add tree traversal in golang #406

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 2 commits into from
Oct 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
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
90 changes: 90 additions & 0 deletions contents/tree_traversal/code/golang/treetraversal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package main

import "fmt"

type node struct {
id int
children []*node
}

func dfsRecursive(n *node) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider returning an array of elements or taking a visitor function, rather than just printing all of them.

That goes for all of these functions, not just this one.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rather have a pointer since it is more memory efficient. I also find it way easier. Tbh i'm not really sure why an array would be better, since now i can build a native tree structure and don't have to build an array and do crazy offset math to figure out the children.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Liikt Yeah, that got shot down in other places too, since we're just demonstrating the algorithm, not trying to build reusable chunks of code. Disregard this one.

fmt.Println(n.id)
for _, child := range n.children {
dfsRecursive(child)
}
}

func dfsRecursivePostorder(n *node) {
for _, child := range n.children {
dfsRecursive(child)
}
fmt.Println(n.id)
}

func dfsRecursiveInorderBtree(n *node) {
switch len(n.children) {
case 2:
dfsRecursiveInorderBtree(n.children[0])
fmt.Println(n.id)
dfsRecursiveInorderBtree(n.children[1])
case 1:
dfsRecursiveInorderBtree(n.children[0])
fmt.Println(n.id)
case 0:
fmt.Println(n.id)
default:
fmt.Println("This is not a binary tree")
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be simplified a bit by running code if lengths are greater than a certain amount, rather than just if they're equal to it. I'm not confident enough with Golang to suggest an alternative without an interpreter handy, but in pseudocode:

if children.length > 2:
  throw "Not a binary tree"

if children.length > 1:
  inOrder(children[1])
printThis()
if children.length > 0:
  inOrder(children[0])

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with you here but I prefer the switch just for readability. It can definitely be made shorter like that though.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Liikt Yup! Which is why I still approved. Both of these were ideas, not must-fixes.

}

func dfsStack(n *node) {
stack := []*node{n}

for len(stack) > 0 {
cur := stack[0]
stack = stack[1:]
fmt.Println(cur.id)
stack = append(cur.children, stack...)
}
}

func bfsQueue(n *node) {
queue := []*node{n}

for len(queue) > 0 {
cur := queue[0]
queue = queue[1:]
fmt.Println(cur.id)
queue = append(queue, cur.children...)
}
}

func createTree(numRow, numChild int) *node {
if numRow == 0 {
return &node{id: 0}
}

cur := new(node)
cur.id = numRow

for x := 0; x < numChild; x++ {
cur.children = append(cur.children, createTree(numRow-1, numChild))
}
return cur
}

func main() {
root := createTree(3, 3)
binTree := createTree(3, 2)

fmt.Println("DFS recursive:")
dfsRecursive(root)
fmt.Println("DFS post order recursive:")
dfsRecursivePostorder(root)
fmt.Println("DFS inorder binary tree:")
dfsRecursiveInorderBtree(binTree)
fmt.Println("DFS stack:")
dfsStack(root)
fmt.Println("BFS queue:")
bfsQueue(root)
}
14 changes: 14 additions & 0 deletions contents/tree_traversal/tree_traversal.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ This has not been implemented in your chosen language, so here is the Julia code
[import:3-27, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:1-5, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:5-8, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

Because of this, the most straightforward way to traverse the tree might be recursive. This naturally leads us to the Depth-First Search (DFS) method:
Expand Down Expand Up @@ -66,6 +68,8 @@ Because of this, the most straightforward way to traverse the tree might be recu
[import:31-35, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:7-10, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:10-15, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

At least to me, this makes a lot of sense. We fight recursion with recursion! First, we first output the node we are on and then we call `DFS_recursive(...)` on each of its children nodes. This method of tree traversal does what its name implies: it goes to the depths of the tree first before going through the rest of the branches. In this case, the ordering looks like:
Expand Down Expand Up @@ -108,6 +112,8 @@ Now, in this case the first element searched through is still the root of the tr
[import:37-41, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:12-15, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:17-22, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

<p>
Expand Down Expand Up @@ -145,6 +151,8 @@ In this case, the first node visited is at the bottom of the tree and moves up t
[import:43-62, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:17-31, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:24-38, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

<p>
Expand Down Expand Up @@ -192,6 +200,8 @@ In code, it looks like this:
[import:64-73, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:33-41, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:40-49, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

All this said, there are a few details about DFS that might not be idea, depending on the situation. For example, if we use DFS on an incredibly long tree, we will spend a lot of time going further and further down a single branch without searching the rest of the data structure. In addition, it is not the natural way humans would order a tree if asked to number all the nodes from top to bottom. I would argue a more natural traversal order would look something like this:
Expand Down Expand Up @@ -231,6 +241,8 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
[import:65-74, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import:43-51, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import:51-60, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}

## Example Code
Expand Down Expand Up @@ -272,6 +284,8 @@ The code snippets were taken from this [Scratch project](https://scratch.mit.edu
[import, lang:"php"](code/php/tree_traversal.php)
{% sample lang="crystal" %}
[import, lang:"crystal"](code/crystal/tree-traversal.cr)
{% sample lang="go" %}
[import, lang:"golang"](code/golang/treetraversal.go)
{% endmethod %}


Expand Down