比较 Golang 中的二叉树。我的答案是错误的。

huangapple go评论95阅读模式
英文:

compare Binary Tree in Golang. my answer is wrong

问题

我将为您翻译以下内容:

我打算在Golang中比较二叉树。但是我的答案是错误的。需要第三只眼睛来帮助。
谢谢。

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链接:
https://play.golang.org/p/mTX3aBxh6_

英文:

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

得分: 1

这一行有一个小错误:

 if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.left)){

应该是:

 if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.right)){

如果你没有看到第二次调用isSameTree的区别,你传递的是q.left,而应该是q.right。

更新后的代码链接:https://play.golang.org/p/ul9ijG9HLc

英文:

This line has a small mistake;

 if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.left)){

It should be;

 if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.right)){

If you don't see the difference in the second call to isSameTree you're passing q.left when it is supposed to be q.right.

Updated go play; https://play.golang.org/p/ul9ijG9HLc

huangapple
  • 本文由 发表于 2015年4月17日 06:10:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/29686888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定