Golang solution (12ms) - Post order traversal


  • 0

    At every node, calculate two things

    • The height of the subtree rooted at that node
    • The max path encountered so far in the subtree rooted at that node
    func diameterOfBinaryTree(root *TreeNode) int {
        _, max := diameterHelper(root)
        return max
    }
    
    func diameterHelper(node *TreeNode) (int, int) {
        if node == nil {return 0, 0}
        left, leftMax := diameterHelper(node.Left)
        right, rightMax:= diameterHelper(node.Right)
        return max(left, right) + 1, max(left + right, max(leftMax, rightMax))
    }
    
    func max(x, y int) int {if x > y {return x}; return y}
    

Log in to reply
 

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