why my GoLang solution is not right, I translated popular java solution directly to golang one.


  • 0
    D
    var max int = 0
    func diameterOfBinaryTree(root *TreeNode) int {
        if root == nil {
            return 0
        }
        ret := helper(root)
        return mymax(max,ret)
    }
    
    func helper(node *TreeNode) int {
       if node == nil {
           return 0
       }  
       left := helper(node.Left)
       right := helper(node.Right)
       max = mymax(max, left+right)
       return mymax(left, right) + 1
    }
    
    func mymax(a, b int) int {
        if a < b {
            return b
        }
        return a
    }
    

  • 0
    D

    @dimi

    var max int = 0
    func diameterOfBinaryTree(root *TreeNode) int {
        if root == nil {
            return 0
        }
        helper(root)
        return max
    }
    
    func helper(node *TreeNode) int {
       if node == nil {
           return 0
       }  
       left := helper(node.Left)
       right := helper(node.Right)
       max = mymax(max, left+right)
       return mymax(left, right) + 1
    }
    
    func mymax(a, b int) int {
        if a < b {
            return b
        }
        return a
    }
    

    This is one is not correct either.
    I am confused.


  • 0
    A
    var max int = 0
    func diameterOfBinaryTree(root *TreeNode) int {
        max = 0 // <-- max is not being reset between test cases without this!!!
        if root == nil {
            return 0
        }
        helper(root)
        return max
    }
    
    func helper(node *TreeNode) int {
       if node == nil {
           return 0
       }  
       left := helper(node.Left)
       right := helper(node.Right)
       max = mymax(max, left+right)
       return mymax(left, right) + 1
    }
    
    func mymax(a, b int) int {
        if a < b {
            return b
        }
        return a
    }
    

    Here's my Go solution:

    func diameterOfBinaryTree(root *TreeNode) int {
    	max := func(i, j int) int {
    		if i > j {
    			return i
    		}
    		return j
    	}
    
    	maxDepth := 0
    	var depth func(*TreeNode) int
    	depth = func(n *TreeNode) int {
    		if n == nil {
    			return 0
    		}
    		ld, rd := depth(n.Left), depth(n.Right)
    		maxDepth = max(maxDepth, ld+rd)
    		return max(ld, rd) + 1
    	}
    
    	if root == nil {
    		return 0
    	}
    
    	// Interesting thing here is that apparently maxDepth is evaluated *after* the depth calls
    	return max(maxDepth, depth(root.Left)+depth(root.Right))
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.