Skip to content

Instantly share code, notes, and snippets.

@fearblackcat
Last active April 15, 2021 22:49
Show Gist options
  • Save fearblackcat/02970015071e63487d964f28f78d938c to your computer and use it in GitHub Desktop.
Save fearblackcat/02970015071e63487d964f28f78d938c to your computer and use it in GitHub Desktop.
traverse the binary tree through golang

Solution to the golang tour's concurrency exercise testing for equivalent binary trees.

Compare with similiar solution presented in golangbootcamp's concurrency chapter.


There can be many different binary trees with the same sequence of values stored at the leaves. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13.

tree

A function to check whether two binary trees store the same sequence is quite complex in most languages. We'll use Go's concurrency and channels to write a simple solution.

This example uses the tree package, which defines the type:

type Tree struct {
    Left  *Tree
    Value int
    Right *Tree
}
  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 ch and kick off the walker:

go Walk(tree.New(1), ch)

Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10.

  1. Implement the Same function using Walk to determine whether t1 and t2 store the same values.

  2. 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.

// Copyright 2011 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 tree

import (
	"fmt"
	"math/rand"
)

// A Tree is a binary tree with integer values.
type Tree struct {
	Left  *Tree
	Value int
	Right *Tree
}

// New returns a new, random binary tree holding the values k, 2k, ..., 10k.
func New(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 + ")"
}



package tree

// Walk recursively walks the tree t sending all values from 
// the tree to the channel ch as found from left to right.
func Walk(t *Tree, ch chan int) {
    if t == nil {
        return
    }
    // walk the left side first
    Walk(t.Left, ch)
    // push the value to the channel
    ch <- t.Value
    // walk the right side last
    Walk(t.Right, ch)
}   

func Walker(t *Tree, ch chan int) {
    // initiate walking over tree t with corresponding channel
    Walk(t, ch)
    // close channel so that range can finish
    close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *Tree) bool {
    if t1 == nil || t2 == nil {
         return false
    }
    c1, c2 := make(chan int), make(chan int)
    go Walker(t1, c1)
    go Walker(t2, c2)
    for v1 := range c1 {
        v2, ok := <- c2
        if !ok {
            return false
        }   
        if v1 != v2 {
            return false
        }   
    }   
    return true
} 

@alexluecke
Copy link

Same(nil, tree.New(2)) will return true.

@BruceWangNo1
Copy link

@alexluecke I have added an if clause to avoid Same(nil, tree.New(2)) returning true. What do you think?

func Same(t1, t2 *Tree) bool {
    c1, c2 := make(chan int), make(chan int)
    go Walker(t1, c1)
    go Walker(t2, c2)
    for v1 := range c1 {
        v2, ok := <- c2
        if !ok {
            return false
        }   
        if v1 != v2 {
            return false
        }   
    }   
    if _, ok := range c2; ok == true {
        return false
    }
 
    return true
} 

@fearblackcat
Copy link
Author

@alexluecke I will add check if clause for channel

@coder-pe
Copy link

coder-pe commented Feb 21, 2021

package main

import (

"fmt"
"golang.org/x/tour/tree"

)

func Walk(t *tree.Tree, ch chan int) {

if t == nil {
    return
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch) 

}

func Same(t1, t2 *tree.Tree) bool {

if t1 == nil || t2 == nil {
    return false
}

c1, c2 := make(chan int), make(chan int)

go Walk(t1, c1)
go Walk(t2, c2)

var v1 int
var v2 int

for i := 0; i < 2; i++ {
    select {
    case v1, _ := <-c1:
        fmt.Printf("v1 = %d\n", v1)
    case v2, _ := <-c2:
        fmt.Printf("v2 = %d\n", v2)
    }
}

if v1 != v2 {
    return false
} 

return true

}

func main() {

ch := make(chan int)

go Walk(tree.New(10), ch)

for i := 0; i < 10; i++ {
    fmt.Println(<-ch)
}
result := Same(tree.New(1), tree.New(1))
fmt.Println(result)

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment