Skip to content

Commit cebd5c6

Browse files
author
Chris Wu
committed
no message
1 parent 50b11c2 commit cebd5c6

File tree

2 files changed

+74
-1
lines changed

2 files changed

+74
-1
lines changed

problems/diameter-of-binary-tree.py

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,59 @@ def traverse(node):
2424

2525
#iterate through the tree
2626
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+

problems/sum-root-to-leaf-numbers.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution(object):
2+
def sumNumbers(self, root):
3+
if not root: return 0
4+
ans = 0
5+
stack = []
6+
stack.append((root, ''))
7+
8+
while stack:
9+
node, total = stack.pop()
10+
total += str(node.val)
11+
if not node.left and not node.right:
12+
ans += int(total)
13+
continue
14+
if node.left:
15+
stack.append((node.left, total))
16+
if node.right:
17+
stack.append((node.right, total))
18+
return ans

0 commit comments

Comments
 (0)