Skip to content

Commit 0f7daa1

Browse files
committed
Adding Simple Solution for Problem 543 - Diameter BT
1 parent a33476d commit 0f7daa1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diameter_BT/SimpleSolution.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 543
6+
## Problem Name: Diameter of Binary Tree
7+
##===================================
8+
#
9+
#Given a binary tree, you need to compute the length of the diameter of the tree.
10+
#The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
11+
#This path may or may not pass through the root.
12+
#
13+
#Example:
14+
#Given a binary tree
15+
# 1
16+
# / \
17+
# 2 3
18+
# / \
19+
# 4 5
20+
#Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
21+
class Solution:
22+
def diameterOfBinaryTree(self, root):
23+
if root is None: #Condition-check: If root is empty
24+
return 0 #We return zero
25+
left = self.length(root.left) #Initialize left and count the length of left sub-tree
26+
right = self.length(root.right) #Initialize right and count the length of right sub-tree
27+
leftDiameter = self.diameterOfBinaryTree(root.left) #Initialize leftDiameter
28+
rightDiameter = self.diameterOfBinaryTree(root.right) #Initialize rightDiameter
29+
return max(left + right, max(leftDiameter, rightDiameter)) #We return max between these two parameters
30+
31+
def length(self, root): #Define length function
32+
if root is None: #Condition-check: If root is empty
33+
return 0 #We return zero
34+
else: #Condition-check: Else
35+
return 1 + max(self.length(root.left), self.length(root.right)) #We return total length for the tree

0 commit comments

Comments
 (0)