Skip to content

Commit

Permalink
Merge df92728 into a10bccc
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Nov 12, 2018
2 parents a10bccc + df92728 commit 3608639
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,4 @@ problems from
* [Day 80](https://github.com/vaskoz/dailycodingproblem-go/issues/168)
* [Day 81](https://github.com/vaskoz/dailycodingproblem-go/issues/171)
* [Day 82](https://github.com/vaskoz/dailycodingproblem-go/issues/173)
* [Day 83](https://github.com/vaskoz/dailycodingproblem-go/issues/175)
17 changes: 17 additions & 0 deletions day83/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package day83

// BinaryTree is a binary tree with string Values.
type BinaryTree struct {
Value string
Left, Right *BinaryTree
}

// InvertBinaryTree works in-place on the given tree.
func InvertBinaryTree(tree *BinaryTree) {
if tree == nil {
return
}
InvertBinaryTree(tree.Left)
InvertBinaryTree(tree.Right)
tree.Left, tree.Right = tree.Right, tree.Left
}
42 changes: 42 additions & 0 deletions day83/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day83

import "testing"

func TestInvertBinaryTree(t *testing.T) {
t.Parallel()
input := &BinaryTree{"a",
&BinaryTree{"b", &BinaryTree{"d", nil, nil}, &BinaryTree{"e", nil, nil}},
&BinaryTree{"c", &BinaryTree{"f", nil, nil}, nil}}
original := &BinaryTree{"a",
&BinaryTree{"b", &BinaryTree{"d", nil, nil}, &BinaryTree{"e", nil, nil}},
&BinaryTree{"c", &BinaryTree{"f", nil, nil}, nil}}
inverted := &BinaryTree{"a",
&BinaryTree{"c", nil, &BinaryTree{"f", nil, nil}},
&BinaryTree{"b", &BinaryTree{"e", nil, nil}, &BinaryTree{"d", nil, nil}}}
InvertBinaryTree(input)
if !equalTrees(input, inverted) {
t.Errorf("Expected it to equal the inverted tree")
}
InvertBinaryTree(input)
if !equalTrees(input, original) {
t.Errorf("Invert an invert should match the original")
}
}

func BenchmarkInvertBinaryTree(b *testing.B) {
input := &BinaryTree{"a",
&BinaryTree{"b", &BinaryTree{"d", nil, nil}, &BinaryTree{"e", nil, nil}},
&BinaryTree{"c", &BinaryTree{"f", nil, nil}, nil}}
for i := 0; i < b.N; i++ {
InvertBinaryTree(input)
}
}

func equalTrees(one, two *BinaryTree) bool {
if one == nil && two == nil {
return true
} else if (one == nil && two != nil) || (one != nil && two == nil) || (one.Value != two.Value) {
return false
}
return equalTrees(one.Left, two.Left) || equalTrees(one.Right, two.Right)
}

0 comments on commit 3608639

Please sign in to comment.