This is a creation in Article, where the information may have evolved or changed.
1. Implement the Walk
function.
2. Test the Walk
function.
The function tree.New(k)
constructs a randomly-structured binary tree holding the values k
,,, 2k
3k
... 10k
.
Create a new channel and ch
kick off the walker:
Go Walk (tree. New (1), CH)
Then read and print ten values from the channel. It should be the numbers 1, 2, 3, ..., 10.
3. Implement the Same
function using to Walk
determine whether and t1
store the t2
same values.
4. Test the Same
function.
Same(tree.New(1), tree.New(1))
Should return true, and Same(tree.New(1), tree.New(2))
should return false.
Package Main
Import (
"Tour/tree"
"FMT"
)
Walk walks the tree t sending all values
From the tree to the channel Ch.
Func Walk (t *tree. Tree, ch Chan int) {
If t.left! = Nil {
Walk (T.left, ch)
}
CH <-t.value
If t.right! = Nil {
Walk (t.right, ch)
}
}
Same determines whether the trees
T1 and T2 contain the same values.
Func Same (t1, T2 *tree. Tree) BOOL {
CH1: = make (chan int)
CH2: = make (chan int)
Go Walk (T1, CH1)
Go Walk (T2, CH2)
For I: = 0; I < 10; i++ {
If <-ch1! = <-ch2 {
return False
}
}
return True
}
Func Main () {
CH: = make (chan int)
Go Walk (tree. New (1), CH)
For I: = 0; I < 10; i++ {
Fmt. Println (<-ch)
}
Fmt. Println ("Equivalent Binary Trees?", Same (tree). New (1), tree. New (1)))
Fmt. Println ("Equivalent Binary Trees?", Same (tree). New (1), tree. New (2)))
}