Last active
August 7, 2020 20:51
-
-
Save cprieto/93111afb923ee9644f3e045876b2a508 to your computer and use it in GitHub Desktop.
Depth-first binary tree traversal modes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// StringNode Is a node in a binary tree | |
type StringNode struct { | |
Data string | |
Left *StringNode | |
Right *StringNode | |
} | |
/* Tree traversal functions (Depth-first traversal) */ | |
type visitor = func(string) | |
// PreOrder Traverse a tree in root-left-right order | |
func (node *StringNode) PreOrder(visit visitor) { | |
if node == nil { | |
return | |
} | |
visit(node.Data) | |
node.Left.PreOrder(visit) | |
node.Right.PreOrder(visit) | |
} | |
// InOrder Traverse a tree in left-root-right order | |
func (node *StringNode) InOrder(visit visitor) { | |
if node == nil { | |
return | |
} | |
node.Left.InOrder(visit) | |
visit(node.Data) | |
node.Right.InOrder(visit) | |
} | |
// PostOrder Traverse a tree in left-right-root order | |
func (node *StringNode) PostOrder(visit visitor) { | |
if node == nil { | |
return | |
} | |
node.Left.PostOrder(visit) | |
node.Right.PostOrder(visit) | |
visit(node.Data) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"strings" | |
"testing" | |
) | |
var tree = StringNode{ | |
Data: "A", | |
Left: &StringNode{ | |
Data: "B", | |
Left: &StringNode{ | |
Data: "E", | |
}, | |
Right: &StringNode{ | |
Data: "F", | |
Left: &StringNode{ | |
Data: "J", | |
}, | |
}, | |
}, | |
Right: &StringNode{ | |
Data: "D", | |
Left: &StringNode{ | |
Data: "H", | |
}, | |
Right: &StringNode{ | |
Data: "I", | |
}, | |
}, | |
} | |
func check(op func(func(string)), expected string, t *testing.T) { | |
var output []string | |
op(func(elem string) { | |
output = append(output, elem) | |
}) | |
if resp := strings.Join(output, " "); resp != expected { | |
t.Errorf("Expected '%v' but got '%v' ", expected, resp) | |
} | |
} | |
func TestPreOrderTreeVisit(t *testing.T) { | |
check(tree.PreOrder, "A B E F J D H I", t) | |
} | |
func TestInOrderTreeVisit(t *testing.T) { | |
check(tree.InOrder, "E B J F A H D I", t) | |
} | |
func TestPostOrderTreeVisit(t *testing.T) { | |
check(tree.PostOrder, "E J F B H I D A", t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment