Skip to content

Commit

Permalink
day 107: add a much faster O(N) solution for level-wise binary tree
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Dec 8, 2018
1 parent c69e21c commit b95bcba
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions day107/problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,24 @@ func max(a, b int) int {
}
return b
}

// BinaryTreeByLevelFaster prints the binary tree level-wise faster than O(N^2).
// This version runs in O(N) with O(N) extra space.
func BinaryTreeByLevelFaster(tree *BinaryTree) []int {
var result []int
level := []*BinaryTree{tree}
for len(level) != 0 {
nextLevel := make([]*BinaryTree, 0, 2*len(level))
for _, node := range level {
result = append(result, node.Value)
if node.Left != nil {
nextLevel = append(nextLevel, node.Left)
}
if node.Right != nil {
nextLevel = append(nextLevel, node.Right)
}
}
level = nextLevel
}
return result
}
17 changes: 17 additions & 0 deletions day107/problem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,20 @@ func BenchmarkBinaryTreeByLevel(b *testing.B) {
}
}
}

func TestBinaryTreeByLevelFaster(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := BinaryTreeByLevelFaster(tc.tree); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func BenchmarkBinaryTreeByLevelFaster(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
BinaryTreeByLevelFaster(tc.tree)
}
}
}

0 comments on commit b95bcba

Please sign in to comment.