1
\$\begingroup\$

Please help me review this code. I want to make it both accurate and more Go-styled.

Go Playground code

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.right)){
        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)
}
\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

A quick way to make your code more Go-styled is to have it automatically formatted. Specifically, spaces are a bit off. For example, in the isSameTree() signature, you have a space before a comma, a space before the closing parenthesis, and no space before the opening brace. The parentheses around (bool) are unnecessary. You're also writing semicolons inconsistently.

The isSameTree() implementation is a bit confusing ("A but not B and not C. If you made it this far, check D and E and F?"). It would be clearer as one long affirmative expression.

func isSameTree(p *TreeNode, q *TreeNode) bool {
        return (p == nil && q == nil) ||
               (p != nil && q != nil &&
                p.val == q.val &&
                isSameTree(p.left, q.left) && isSameTree(p.right, q.right))
}
\$\endgroup\$
1
\$\begingroup\$

https://play.golang.org/p/JSt3HtE29C

Changes:

  • tidy the definition of TreeNode by sharing the type for left and right.
  • simplify the tests for p and q being nil.
  • Removing braces from the if condition
  • if <x> { return true } else { return false } is better written return <x>.

Here's the changed code:

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

func isSameTree(p *TreeNode, q *TreeNode) bool {
    if p == nil || q == nil {
        return p == q
    }
    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.