Skip to content

Commit 9907199

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

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diameter_BT/EfficientSolution.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
self.tmp = 0 #Initialize tmp = 0
24+
length = self.dfs(root) #Initialize length, which is after running dfs, we'll get the count
25+
return tmp #We'll return tmp
26+
def dfs(self, node): #Define DFS
27+
if node is None: #Condition-check: If node is empty
28+
return 0 #We return 0
29+
l, r = self.dfs(node.left), self.dfs(node.right) #Initialize l and r
30+
self.tmp = max(self.tmp, l + r) #Update tmp by finding max between tmp and l + r
31+
return 1 + max(l, r) #Return 1 + max between l and r

0 commit comments

Comments
 (0)