Python with explanation - Beats more than 80%


  • 0
    K
    def diameterOfBinaryTree(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            
            self.diam=0
             
            def depth(root):
                
                if root:
                    left= depth(root.left)
                    right = depth(root.right)
                    self.diam = max(self.diam, 2+left+right)
                    return 1+ max(left,right)
                else:
                    return -1
                
            depth(root)
            return self.diam
    

    *A recursive function depth() measures depth where the leaf nodes are at depth 0.To achieve this we make the Null or None pointers return -1. This makes leaf nodes with 0 depth.
    *At any node then the diameter will simply be 2+ depth of left sub-tree + depth of right sub-tree.


Log in to reply
 

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