dth20986
dth20986
2015-04-16 22:10

比较Golang中的Binary Tree。 我的答案是错误的

  • pointers

I am going to compare Binary Tree in Golang.But my answer is wrong. Need the third eye to help. Thanks.

package main

import(
    "fmt"
)

type TreeNode struct {
    val int
    left *TreeNode
    right *TreeNode

}

func isSameTree(p *TreeNode , q *TreeNode ) (bool){
    if p == nil && q == nil {
        return true
    } 
    if p != nil && q == nil{
        return false;
    }
    if p ==nil && q != nil {
        return false;
    }
    if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.left)){
        return true;
    } else {
        return false;
    }
}
func main(){
    p := &TreeNode{val: 1}
    p.left = &TreeNode{val: 2}
    p.right = &TreeNode{val: 3}

    q := &TreeNode{val: 1}
    q.left = &TreeNode{val: 2}
    q.right = &TreeNode{val: 3}

    isSame := isSameTree(p,q)
    fmt.Println("is same?: ", isSame)
}

Go playground link for this code: https://play.golang.org/p/mTX3aBxh6_

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐

换一换