英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论