Created
May 10, 2025 19:59
-
-
Save martin-mok/8f647bfb25d7c645fa154512b4040b91 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees
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
// Copyright 2012 The Go Authors. All rights reserved. | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
package main | |
import ( | |
"fmt" | |
"code.google.com/p/go-tour/tree" | |
) | |
func walkImpl(t *tree.Tree, ch chan int) { | |
if t.Left != nil { | |
walkImpl(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
walkImpl(t.Right, ch) | |
} | |
} | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
walkImpl(t, ch) | |
// Need to close the channel here | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
w1, w2 := make(chan int), make(chan int) | |
go Walk(t1, w1) | |
go Walk(t2, w2) | |
for { | |
v1, ok1 := <-w1 | |
v2, ok2 := <-w2 | |
if v1 != v2 || ok1 != ok2 { | |
return false | |
} | |
if !ok1 { | |
break | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Print("tree.New(1) == tree.New(1): ") | |
if Same(tree.New(1), tree.New(1)) { | |
fmt.Println("PASSED") | |
} else { | |
fmt.Println("FAILED") | |
} | |
fmt.Print("tree.New(1) != tree.New(2): ") | |
if !Same(tree.New(1), tree.New(2)) { | |
fmt.Println("PASSED") | |
} else { | |
fmt.Println("FAILED") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment