41. Equivalent binary tree

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Implements a comparison of two binary trees. Binary tree basic types and functions from "Golang.org/x/tour/tree", in order to avoid network problems affecting the code to run, I put the source directly into the code.

 //A tree is a binary tree with an 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 {t = insert (t, (1+V) *k)} return t}func insert (t *tree, v int) *tree {if T = = Nil {Retu RN &tree{nil, V, nil}} if v < t.value {t.left = insert (T.left, V)} else {t.right = Inser T (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 + ")"}  

The above code implements the basic functions of the two-fork tree. Let's make a comparison of the two fork trees.
The two binary trees are to be compared for consistency. We set up a function. Same (t1, T2 *tree) bool
In order to compare binary trees, it is necessary to put the value of the two-fork tree into one channel. A total of two channels are used for comparison. The function that is put into the channel we establish as Walk (t *tree, ch Chan int) and then establish a recursive function to traverse all the leaf nodes of the binary tree Rangetree (t *tree, ch Chan int)

//遍历二叉树,把当前节点值传入通道func rangeTree(t *Tree, ch chan int)  {    if t != nil{        rangeTree(t.Left, ch)        ch <- t.Value        rangeTree(t.Right, ch)    }}// Walk 步进 tree t 将所有的值从 tree 发送到 channel ch。func Walk(t *Tree, ch chan int){    rangeTree(t, ch)    close(ch)}// Same 检测树 t1 和 t2 是否含有相同的值。func Same(t1, t2 *Tree) bool{    //建立两个通道    ch1 := make(chan int)    ch2 := make(chan int)    //遍历两个二叉树,把值传入各自的通道    go Walk(t1, ch1)    go Walk(t2, ch2)    //遍历通道进行比较,有不同的值就返回false    for i := range ch1{        if i != <- ch2{            return false        }    }    return true}

Then compare the two tree in the main function

    fmt.Println(Same(New(1), New(1)))    fmt.Println(Same(New(1), New(2)))

Complete code example

Package Mainimport ("FMT" "Math/rand")//a tree is a binary tree with an integer values.type tree struct {left *t Ree 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 {t = insert (t, (1+V) *k)} return t}func insert (t *tree, v int) *tree {if T = = Nil {Retu RN &tree{nil, V, nil}} if v < t.value {t.left = insert (T.left, V)} else {t.right = Inser T (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 + ")"}//Walk stepping tree T will All values are sent from the tree to channel Ch.  Func Walk (t *tree, ch Chan int) {rangetree (T, ch) close (CH)}//traverse the binary tree, passing the current node value into the channel func Rangetree (t *tree, ch Chan int) {   If T! = nil{rangetree (t.left, ch) ch <-t.value rangetree (t.right, ch)}}//same detection tree T1 and T 2 contains the same value. Func Same (t1, T2 *tree) bool{//Establish two channels ch1: = make (chan int) CH2: = make (chan int)//traverse two binary trees, pass the values to the respective channel go W ALK (t1, ch1) go Walk (T2, CH2)//Traversal channel for comparison, with different values returning false for I: = range ch1{If I! = <-ch2{R Eturn false}} return True}func main () {FMT. PRINTLN ("Binary tree Traversal comparison") FMT.        Println ("Print the value of new (1)")//print the value of new (1) var ch1 = make (chan int) go Walk (New (1), CH1) for V: = Range ch1{ Fmt. Println (v)} FMT.        Println ("Print the value of new (2)")//print the value of new (2) var CH2 = make (chan int) go Walk (New (2), CH2) for V: = Range ch2{ Fmt. Println (v)}//compares the values of two tree to the FMT. Println (Same (new (1), new (1)) fmt. Println (Same (new (1), New (2))}

Run results

二叉树遍历比较打印 New(1)的值12345678910打印 New(2)的值2468101214161820truefalse

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.