@@ -24,4 +24,59 @@ def traverse(node):
24
24
25
25
#iterate through the tree
26
26
traverse (root )
27
- return self .diameter
27
+ return self .diameter
28
+
29
+ #2020
30
+ class Solution (object ):
31
+ def diameterOfBinaryTree (self , root ):
32
+ def getMaxDepth (node ):
33
+ if not node : return 0
34
+
35
+ l , r = getMaxDepth (node .left ), getMaxDepth (node .right )
36
+ self .ans = max (self .ans , l + r )
37
+ return max (l , r )+ 1 #add the node it self
38
+
39
+ if not root : return 0
40
+ self .ans = float ('-inf' )
41
+ getMaxDepth (root )
42
+ return self .ans
43
+ """
44
+ What we want to find?
45
+ From an unknown node, that its max_depth_from_left (`l`) + max_depth_from_right (`r`) is the biggest.
46
+ The node that generate this number could be from any node, so we iterate through every node to update `ans`.
47
+ In other words, to find the answer, we need to check every node, if the max diameter pass through here.
48
+ """
49
+
50
+ # from collections import defaultdict
51
+ # class Solution(object):
52
+ # def diameterOfBinaryTree(self, root):
53
+ # def getLeftLength(node):
54
+ # if not node: return -1
55
+ # if not (node in record and 'left' in record[node]):
56
+ # record[node]['left'] = max(getLeftLength(node.left), getRightLength(node.left))+1
57
+ # return record[node]['left']
58
+
59
+ # def getRightLength(node):
60
+ # if not node: return -1
61
+ # if not (node in record and 'right' in record[node]):
62
+ # record[node]['right'] = max(getLeftLength(node.right), getRightLength(node.right))+1
63
+ # return record[node]['right']
64
+
65
+ # if not root: return 0
66
+
67
+ # record = defaultdict(dict)
68
+ # ans = float('-inf')
69
+ # stack = []
70
+ # stack.append(root)
71
+
72
+ # while stack:
73
+ # node = stack.pop()
74
+ # if not node: continue
75
+
76
+ # d = getLeftLength(node)+getRightLength(node)
77
+ # ans = max(ans, d)
78
+ # stack.append(node.left)
79
+ # stack.append(node.right)
80
+
81
+ # return ans
82
+
0 commit comments