⬅ Previous Topic
Find Height of a Binary TreeNext Topic ⮕
Find Mirror of a Binary Tree - Todo⬅ Previous Topic
Find Height of a Binary TreeNext Topic ⮕
Find Mirror of a Binary Tree - Todomax(left, right) + 1
.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def diameterOfBinaryTree(root):
diameter = 0
def height(node):
nonlocal diameter
if not node:
return 0
left = height(node.left)
right = height(node.right)
diameter = max(diameter, left + right)
return max(left, right) + 1
height(root)
return diameter
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
print(diameterOfBinaryTree(root))
⬅ Previous Topic
Find Height of a Binary TreeNext Topic ⮕
Find Mirror of a Binary Tree - TodoYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.