Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create 543_Diameter_Of_Binary_Tree.py #1062

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Python/543_Diameter_Of_Binary_Tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def diameterTreeUtil(root):
if root == None: return [0,0]

leftTree = diameterTreeUtil(root.left)
rightTree = diameterTreeUtil(root.right)

internalPath = max(leftTree[1],rightTree[1])
if leftTree[0] + rightTree[0] + 1 > internalPath: internalPath = leftTree[0] + rightTree[0] + 1

return [max(leftTree[0],rightTree[0])+1,internalPath]

if root == None: return 0
result = diameterTreeUtil(root)
return max(result)-1