Diameter of Binary Tree - Better Design

前端 未结 11 2064
闹比i
闹比i 2020-12-23 15:14

I have written a code for finding diameter of Binary Tree. Need suggestions for the following:

  1. Can I do this without using static variable at class level?
11条回答
  •  不知归路
    2020-12-23 15:59

    The most efficient way is to compute diameter along with height to get to O(n) and here is the easiest way to get so [Python3,PyPy3]

    for this definition for a binary tree node,
    class TreeNode:
         def __init__(self, x):
             self.val = x
             self.left = None
             self.right = None
    
    class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.height = 1
    
        def height(node):
            if node is None:
                return 0
            l_height = height(node.left)
            r_height = height(node.right)
            self.height = max(self.height,l_height+r_height+1)
            return max(l_height,r_height) + 1
    
        height(root)
        return self.height-1
    

    The most simplest and affordable solution with faster runtime and lower complexity.

提交回复
热议问题