Skip to content

Commit c09736a

Browse files
Add solutions to LC110 and LC58
1 parent 2ba2de0 commit c09736a

File tree

3 files changed

+221
-0
lines changed

3 files changed

+221
-0
lines changed

LC110-Balanced-Binary-Tree.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Given a binary tree, determine if it is height-balanced.
3+
4+
For this problem, a height-balanced binary tree is defined as:
5+
6+
a binary tree in which the left and right subtrees of every
7+
node differ in height by no more than 1.
8+
9+
Example 1.
10+
Input: root = [3,9,20,null,null,15,7]
11+
Output: true
12+
13+
Example 2.
14+
Input: root = [1,2,2,3,3,null,null,4,4]
15+
Output: false
16+
17+
Example 3:
18+
Input: root = []
19+
Output: true
20+
21+
22+
Constraints:
23+
(*) The number of nodes in the tree is in the range [0, 5000].
24+
(*)-10^4 <= Node.val <= 10^4
25+
"""
26+
from TreeNode import TreeNode
27+
28+
29+
class Solution:
30+
def isBalanced(self, root: TreeNode) -> bool:
31+
"""
32+
Checking isBalanced using new depth attribute
33+
Time complexity: O(n)
34+
Space complexity: O(n)
35+
"""
36+
if root is None: return True
37+
38+
if root.left is not None:
39+
is_left_balanced = self.isBalanced(root.left)
40+
left_depth = root.left.depth
41+
else:
42+
is_left_balanced = True
43+
left_depth = 0
44+
45+
if root.right is not None:
46+
is_right_balanced = self.isBalanced(root.right)
47+
right_depth = root.right.depth
48+
else:
49+
is_right_balanced = True
50+
right_depth = 0
51+
52+
# determine the depth
53+
root.depth = max(right_depth, left_depth) + 1
54+
55+
# determine if the node is balanced
56+
root.is_balanced = is_left_balanced and is_right_balanced and abs(right_depth - left_depth) <= 1
57+
return root.is_balanced
58+
59+
60+
if __name__ == '__main__':
61+
from run_tests import run_tests
62+
63+
correct_answers = [
64+
[[3, 9, 20, None, None, 15, 7], True],
65+
[[1,2,2,3,3,None,None,4,4], False],
66+
[[], True]
67+
]
68+
correct_answers = [
69+
[TreeNode.to_treenode(lst), ans] for lst, ans in correct_answers
70+
]
71+
print('Run tests for isBalanced')
72+
run_tests(Solution().isBalanced, correct_answers)

LC58-Length-of-Last-Word.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Given a string s consists of some words separated by spaces,
3+
return the length of the last word in the string. If the last
4+
word does not exist, return 0.
5+
6+
A word is a maximal substring consisting of non-space characters only.
7+
8+
Example 1:
9+
Input: s = "Hello World"
10+
Output: 5
11+
12+
Example 2:
13+
Input: s = " "
14+
Output: 0
15+
16+
17+
Constraints:
18+
(*) 1 <= s.length <= 104
19+
(*) s consists of only English letters and spaces ' '.
20+
"""
21+
22+
23+
class Solution:
24+
def lengthOfLastWord2(self, s: str) -> int:
25+
"""
26+
Time complexity: O(n)
27+
Space complexity: O(1)
28+
"""
29+
word_started = False
30+
l = 0
31+
for i in range(len(s) - 1, -1, -1):
32+
if s[i] == ' ' and word_started:
33+
return l
34+
35+
elif s[i] != ' ':
36+
word_started = True
37+
l += 1
38+
39+
return l
40+
41+
def lengthOfLastWord(self, s: str) -> int:
42+
"""
43+
Time complexity: O(n)
44+
Space complexity: O(n)
45+
"""
46+
s = s.split()
47+
return len(s[-1]) if s else 0
48+
49+
50+
if __name__ == '__main__':
51+
from run_tests import run_tests
52+
53+
correct_answers = [
54+
['', 0],
55+
[' ', 0],
56+
[' ', 0],
57+
['word', 4],
58+
['Hello World', 5],
59+
['Hello Worlds ', 6]
60+
]
61+
methods = ['lengthOfLastWord', 'lengthOfLastWord2', ]
62+
for method in methods:
63+
print(f'Running tests for {method}')
64+
run_tests(getattr(Solution(), method), correct_answers)

TreeNode.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from typing import List
2+
3+
4+
class IncorrectTreeNodeTranscription(Exception):
5+
pass
6+
7+
8+
class TreeNode:
9+
def __init__(self, val=0, left=None, right=None):
10+
self.val = val
11+
self.left = left
12+
self.right = right
13+
14+
def to_list(self) -> List[int or str]:
15+
level = [self, ]
16+
lst = []
17+
while level:
18+
new_level = list()
19+
for node in level:
20+
if node is None:
21+
lst.append(None)
22+
else:
23+
lst.append(node.val)
24+
new_level.append(node.left)
25+
new_level.append(node.right)
26+
level = list(new_level)
27+
28+
return lst
29+
30+
@classmethod
31+
def to_treenode(cls, arr: List[int or str]) -> 'TreeNode' or None:
32+
if not arr or arr[0] is None:
33+
return None
34+
35+
level = [TreeNode(arr.pop(0)), ]
36+
root = level[0]
37+
while level:
38+
new_level = []
39+
for node in level:
40+
if not arr:
41+
break
42+
elif arr[0] is None:
43+
arr.pop(0)
44+
else:
45+
node.left = TreeNode(arr.pop(0))
46+
new_level.append(node.left)
47+
48+
if not arr:
49+
break
50+
elif arr[0] is None:
51+
arr.pop(0)
52+
else:
53+
node.right = TreeNode(arr.pop(0))
54+
new_level.append(node.right)
55+
level = list(new_level)
56+
return root
57+
58+
def __repr__(self):
59+
return str(self.to_list())
60+
61+
def __eq__(self, other):
62+
this = self
63+
if this is None and other is None:
64+
return True
65+
66+
if this is None or other is None:
67+
return False
68+
69+
if this.val != other.val:
70+
return False
71+
72+
return self.left == other.left and self.right == other.right
73+
74+
75+
if __name__ == '__main__':
76+
lists = [
77+
[1, None, None],
78+
[1, 2, None, None, 3, None, None],
79+
[1,None,2,None,3, None, None],
80+
[1, 4, None, None, 3, None, None],
81+
[3,9,20,None,None, 15, 7]
82+
]
83+
for lst in lists:
84+
lst2 = TreeNode.to_treenode(list(lst)).to_list()
85+
assert lst2 == lst + [None, ] * (len(lst2) - len(lst)), str(lst)

0 commit comments

Comments
 (0)