Created
January 9, 2018 08:36
-
-
Save lucasponce/ab06634fec18f4675246028f9be0b62e to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"fmt" | |
) | |
type Tree struct { | |
Left *Tree | |
Value int | |
Right *Tree | |
} | |
var ( | |
tree1 = Tree{ | |
&Tree{ | |
&Tree{nil, 1, nil}, | |
1, | |
&Tree{nil, 2, nil}, | |
}, | |
3, | |
&Tree{ | |
&Tree{nil, 5, nil}, | |
8, | |
&Tree{nil, 13, nil}, | |
}, | |
} | |
tree2 = Tree{ | |
&Tree{ | |
&Tree{ | |
&Tree{nil, 1, nil}, | |
1, | |
&Tree{nil, 2, nil}}, | |
3, | |
&Tree{nil, 5, nil}, | |
}, | |
8, | |
&Tree{nil, 13, nil}, | |
} | |
tree3 = Tree{ | |
&Tree{ | |
&Tree{ | |
&Tree{nil, 1, nil}, | |
1, | |
&Tree{nil, 2, nil}}, | |
3, | |
&Tree{nil, 5, nil}, | |
}, | |
8, | |
&Tree{nil, 14, nil}, | |
} | |
) | |
func Walk(treeName string, tree *Tree, ch chan int) { | |
recWalk(treeName, tree, ch) | |
close(ch) | |
} | |
func recWalk(treeName string, tree *Tree, ch chan int) { | |
if tree != nil { | |
recWalk(treeName, tree.Left, ch) | |
ch <- tree.Value | |
if tree.Value == 13 { | |
fmt.Println("Here will be a breakpoint") | |
} | |
recWalk(treeName, tree.Right, ch) | |
} | |
} | |
func Same(t1, t2 *Tree) bool { | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go Walk("tree1", t1, ch1) | |
go Walk("tree2", t2, ch2) | |
for { | |
x1, ok1 := <- ch1 | |
x2, ok2 := <- ch2 | |
switch { | |
case ok1 != ok2: | |
// One channel finishes earlier, so not same size | |
return false | |
case !ok1: | |
// Both channels are empty | |
return true | |
case x1 != x2: | |
// Elements are different | |
return false | |
default: | |
} | |
} | |
} | |
func main() { | |
fmt.Println("Binary Tree exercice") | |
fmt.Println(Same(&tree1, &tree2)) | |
fmt.Println(Same(&tree1, &tree3)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment