Created
April 2, 2022 08:12
-
-
Save Virviil/04edb01b436e059cb3ec4c5404b928a0 to your computer and use it in GitHub Desktop.
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 ( | |
"fmt" | |
"math/rand" | |
) | |
type Tree struct { | |
Left *Tree | |
Value int | |
Right *Tree | |
} | |
// NewTree returns a new, random binary tree holding the values k, 2k, ..., 10k. | |
func NewTree(k int) *Tree { | |
var t *Tree | |
for _, v := range rand.Perm(10) { | |
t = insert(t, (1+v)*k) | |
} | |
return t | |
} | |
func insert(t *Tree, v int) *Tree { | |
if t == nil { | |
return &Tree{nil, v, nil} | |
} | |
if v < t.Value { | |
t.Left = insert(t.Left, v) | |
} else { | |
t.Right = insert(t.Right, v) | |
} | |
return t | |
} | |
func (t *Tree) String() string { | |
if t == nil { | |
return "()" | |
} | |
s := "" | |
if t.Left != nil { | |
s += t.Left.String() + " " | |
} | |
s += fmt.Sprint(t.Value) | |
if t.Right != nil { | |
s += " " + t.Right.String() | |
} | |
return "(" + s + ")" | |
} | |
func Walk(t *Tree, ch chan int, n int) { | |
if t.Left != nil { | |
Walk(t.Left, ch, n) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
Walk(t.Right, ch, n) | |
} | |
} | |
func Same(t1, t2 *Tree) bool { | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go func() { | |
Walk(t1, ch1, 1) | |
close(ch1) | |
}() | |
go func() { | |
Walk(t2, ch2, 2) | |
close(ch2) | |
}() | |
for { | |
v1, ok1 := <- ch1 | |
v2, ok2 := <- ch2 | |
if ok1 == false && ok2 == false { | |
return true | |
} | |
if v1 != v2 { | |
return false | |
} | |
} | |
} | |
func main() { | |
t1 := NewTree(10) | |
t2 := NewTree(10) | |
println(Same(t1, t2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment