diff --git a/exercise/equal-binary-tree/README.md b/exercise/equal-binary-tree/README.md new file mode 100644 index 0000000..1adc2a5 --- /dev/null +++ b/exercise/equal-binary-tree/README.md @@ -0,0 +1,68 @@ +## Test cases + + + +### Test Case 1 + +``` +fmt.Println(Same(tree.New(1), tree.New(1))) +``` + +**output** +``` + +``` + + +### Test Case 2 + +``` +t := tree.New(1) +fmt.Println(Same(t, t)) +``` + +**output** +``` +ch2 +10 +ch1 +10 +ch2 +5 +ch1 +5 +ch2 +3 +ch1 +3 +ch2 +2 +ch1 +2 +ch2 +7 +ch1 +7 +ch2 +9 +ch1 +9 +ch2 +8 +ch1 +8 +ch2 done +0 +true +``` + + + +### Test Case 3 + +``` +fmt.Println(Same(tree.New(1), tree.New(2))) +``` + +**output** + diff --git a/exercise/equal-binary-tree/main.go b/exercise/equal-binary-tree/main.go new file mode 100644 index 0000000..38aec63 --- /dev/null +++ b/exercise/equal-binary-tree/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + + "golang.org/x/tour/tree" +) + +func Walk(t *tree.Tree, ch chan int) { + walk(t, ch) + close(ch) +} + +// walk traverses the tree by the pre-order +func walk(t *tree.Tree, ch chan int) { + if t != nil { + ch <- t.Value + + walk(t.Left, ch) + + walk(t.Right, ch) + } + +} + +func Same(t1, t2 *tree.Tree) bool { + + ch1 := make(chan int) + ch2 := make(chan int) + + go Walk(t1, ch1) + go Walk(t2, ch2) + + x, y := 0, 0 + ok := true + for { + select { + case x, ok = <-ch1: + if !ok { + return true + } + y = <-ch2 + if x != y { + return false + } + + case x, ok = <-ch2: + if !ok { + fmt.Println("ch2 done") + fmt.Println(x) + return true + } + fmt.Println("ch2") + fmt.Println(x) + y = <-ch1 + fmt.Println("ch1") + fmt.Println(y) + if x != y { + return false + } + } + } + + return true +} + +func main() { + + // fmt.Println(Same(tree.New(1), tree.New(1))) + + t := tree.New(1) + fmt.Println(Same(t, t)) + + // fmt.Println(Same(tree.New(1), tree.New(2))) +}