github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/go4gophers/tree-nothread.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"code.google.com/p/go-tour/tree"
     9  )
    10  
    11  func Walk(root *tree.Tree) *Walker {
    12  	return &Walker{stack: []*frame{{t: root}}}
    13  }
    14  
    15  type Walker struct {
    16  	stack []*frame
    17  }
    18  
    19  type frame struct {
    20  	t  *tree.Tree
    21  	pc int
    22  }
    23  
    24  func (w *Walker) Next() (int, bool) {
    25  	if len(w.stack) == 0 {
    26  		return 0, false
    27  	}
    28  
    29  	// continued next slide ...
    30  	// CUT OMIT
    31  	f := w.stack[len(w.stack)-1]
    32  	if f.pc == 0 {
    33  		f.pc++
    34  		if l := f.t.Left; l != nil {
    35  			w.stack = append(w.stack, &frame{t: l})
    36  			return w.Next()
    37  		}
    38  	}
    39  	if f.pc == 1 {
    40  		f.pc++
    41  		return f.t.Value, true
    42  	}
    43  	if f.pc == 2 {
    44  		f.pc++
    45  		if r := f.t.Right; r != nil {
    46  			w.stack = append(w.stack, &frame{t: r})
    47  			return w.Next()
    48  		}
    49  	}
    50  	w.stack = w.stack[:len(w.stack)-1]
    51  	return w.Next()
    52  }
    53  
    54  // STOP OMIT
    55  
    56  func Same(t1, t2 *tree.Tree) bool {
    57  	w1, w2 := Walk(t1), Walk(t2)
    58  	for {
    59  		v1, ok1 := w1.Next()
    60  		v2, ok2 := w2.Next()
    61  		if v1 != v2 || ok1 != ok2 {
    62  			return false
    63  		}
    64  		if !ok1 {
    65  			return true
    66  		}
    67  	}
    68  }
    69  
    70  func main() {
    71  	fmt.Println(Same(tree.New(3), tree.New(3)))
    72  	fmt.Println(Same(tree.New(1), tree.New(2)))
    73  }