I have written a code for finding diameter of Binary Tree. Need suggestions for the following:
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.