Skip to content

Commit 6fb6205

Browse files
Kurt-Yuhaoel
authored andcommitted
add python solution to some questions
1 parent 3e3321a commit 6fb6205

File tree

9 files changed

+176
-3
lines changed

9 files changed

+176
-3
lines changed

README.md

+8-3
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,19 @@ LeetCode
88

99
| # | Title | Solution | Difficulty |
1010
|---| ----- | -------- | ---------- |
11+
|951|[Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) | [Python](./algorithms/python/FlipEquivalentBinaryTrees/flipEquiv.py)|Medium|
1112
|859|[Buddy Strings](https://leetcode.com/problems/buddy-strings/description/) | [C++](./algorithms/cpp/buddyStrings/BuddyStrings.cpp)|Easy|
1213
|858|[Mirror Reflection](https://leetcode.com/problems/mirror-reflection/description/) | [C++](./algorithms/cpp/mirrorReflection/MirrorReflection.cpp)|Medium|
1314
|852|[Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) | [C++](./algorithms/cpp/peakIndexInAMountainArray/PeakIndexInAMountainArray.cpp)|Easy|
1415
844|[Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/description/) | [C++](./algorithms/cpp/backspaceStringCompare/BackspaceStringCompare.cpp)|Easy|
1516
|837|[Most Common Word](https://leetcode.com/problems/most-common-word/) | [C++](./algorithms/cpp/mostCommonWord/MostCommonWord.cpp)|Easy|
1617
|804|[Unique Morse Code Words](https://leetcode.com/problems/unique-morse-code-words/description/) | [C++](./algorithms/cpp/uniqueMorseCodeWords/UniqueMorseCodeWords.cpp)|Easy|
1718
|771|[Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/description) | [C++](./algorithms/cpp/jewelsAndStones/JewelsAndStones.cpp)|Easy|
19+
|684|[Redundant Connection](https://leetcode.com/problems/redundant-connection/) | [Python](./algorithms/python/RedundantConnection/findRedundantConnection.py)|Medium|
20+
|671|[Second Minimum Node In a Binary Tree](https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/) | [Python](./algorithms/python/SecondMinimumNodeInABinaryTree/findSecondMinimumValue.py)|Easy|
21+
|655|[Print Binary Tree](https://leetcode.com/problems/print-binary-tree/) | [Python](./algorithms/python/PrintBinaryTree/printTree.py)|Medium|
1822
|643|[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/description/) | [C++](./algorithms/cpp/maximumAverageSubarray/MaximumAverageSubarray.I.cpp)|Easy|
23+
|538|[Convert BST to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) | [Python](./algorithms/python/ConvertBSTtoGreaterTree/convertBST.py)|Easy|
1924
|477|[Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./algorithms/cpp/totalHammingDistance/totalHammingDistance.cpp)|Medium|
2025
|418|[SentenceScreenFitting](https://leetcode.com/problems/sentence-screen-fitting/) ♥ | [C++](./algorithms/cpp/sentenceScreenFitting/sentenceScreenFitting.cpp)|Easy|
2126
|416|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/description/) | [C++](./algorithms/cpp/partitionEqualSubsetSum/PartitionEqualSubsetSum.cpp)|Medium|
@@ -27,7 +32,7 @@ LeetCode
2732
|409|[Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | [C++](./algorithms/cpp/longestPalindrome/LongestPalindrome.cpp)|Easy|
2833
|406|[Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/) | [C++](./algorithms/cpp/queueReconstructionByHeight/QueueReconstructionByHeight.cpp)|Medium|
2934
|405|[Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/) | [C++](./algorithms/cpp/convertANumberToHexadecimal/ConvertANumberToHexadecimal.cpp)|Easy|
30-
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp)|Easy|
35+
|404|[Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | [C++](./algorithms/cpp/sumOfLeftLeaves/SumOfLeftLeaves.cpp), [Python] (./algorithms/python/SumOfLeftLeaves/sumOfLeftLeaves.py)|Easy|
3136
|403|[Frog Jump](https://leetcode.com/problems/frog-jump/) | [C++](./algorithms/cpp/frogJump/FrogJump.cpp)|Hard|
3237
|402|[Remove K Digits](https://leetcode.com/problems/remove-k-digits/) | [C++](./algorithms/cpp/removeKDigits/RemoveKDigits.cpp)|Medium|
3338
|401|[Binary Watch](https://leetcode.com/problems/binary-watch/) | [C++](./algorithms/cpp/binaryWatch/BinaryWatch.cpp)|Easy|
@@ -119,12 +124,12 @@ LeetCode
119124
|238|[Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)| [C++](./algorithms/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp)|Medium|
120125
|237|[Delete Node in a Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/)| [C++](./algorithms/cpp/deleteNodeInALinkedList/DeleteNodeInALinkedList.cpp)|Easy|
121126
|236|[Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| [C++](./algorithms/cpp/lowestCommonAncestorOfABinaryTree/LowestCommonAncestorOfABinaryTree.cpp), [Java](./algorithms/java/src/lowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTree.java)|Medium|
122-
|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| [C++](./algorithms/cpp/lowestCommonAncestorOfABinarySearchTree/LowestCommonAncestorOfABinarySearchTree.cpp)|Easy|
127+
|235|[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| [C++](./algorithms/cpp/lowestCommonAncestorOfABinarySearchTree/LowestCommonAncestorOfABinarySearchTree.cpp), [Python](./algorithms/python/LowestCommonAncestorOfABinarySearchTree/lowestCommonAncestor.py)|Easy|
123128
|234|[Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/)| [C++](./algorithms/cpp/palindromeLinkedList/PalindromeLinkedList.cpp)|Easy|
124129
|233|[Number of Digit One](https://leetcode.com/problems/number-of-digit-one/)| [C++](./algorithms/cpp/numberOfDigitOne/NumberOfDigitOne.cpp)|Medium|
125130
|232|[Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)| [C++](./algorithms/cpp/implementQueueUsingStacks/ImplementQueueUsingStacks.cpp), [Java](./algorithms/java/src/myQueue/MyQueue.java)|Easy|
126131
|231|[Power of Two](https://leetcode.com/problems/power-of-two/)| [C++](./algorithms/cpp/powerOfTwo/PowerOfTwo.cpp)|Easy|
127-
|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [C++](./algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp)|Medium|
132+
|230|[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| [C++](./algorithms/cpp/kthSmallestElementInaBST/KthSmallestElementInABst.cpp), [Python] (./algorithms/python/KthSmallestElementInABST/kthSmallest.py)|Medium|
128133
|229|[Majority Element II](https://oj.leetcode.com/problems/majority-element-ii/) | [C++](./algorithms/cpp/majorityElement/majorityElement.II.cpp)|Medium|
129134
|228|[Summary Ranges](https://leetcode.com/problems/summary-ranges/)| [C++](./algorithms/cpp/summaryRanges/SummaryRanges.cpp)|Easy|
130135
|227|[Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)| [C++](./algorithms/cpp/basicCalculator/BasicCalculator.II.cpp)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
since this is a BST, we can do a inorder traversal (inversed, from right to left),
3+
during this process, track the sum and update the node.val
4+
"""
5+
6+
class Solution:
7+
def convertBST(self, root):
8+
self.total = 0
9+
10+
def helper(node):
11+
if not node: return
12+
helper(node.right)
13+
node.val += self.total
14+
self.total = node.val
15+
helper(node.left)
16+
17+
helper(root)
18+
return root
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Method 1:
3+
naive recursive solution, divide the original problem into four subproblems,
4+
time complexity and space complexity are both O(n^2)
5+
"""
6+
def flipEquiv1(self, root1, root2):
7+
if not root1 or not root2:
8+
return root1 == root2
9+
if root1.val != root2.val:
10+
return False
11+
return self.flipEquiv(root1.left, root2.left) and \
12+
self.flipEquiv(root1.right, root2.right) or \
13+
self.flipEquiv(root1.left, root2.right) and \
14+
self.flipEquiv(root1.right, root2.left)
15+
16+
"""
17+
Method 2:
18+
Step 1: first preprocessing these two trees, sort them in the following order:
19+
if node.left.val > node.right.val, then swap them, make the smaller one to be left node
20+
if the left node is None, then also swap them, make the non-None node to be left node
21+
22+
Step 2: compare the swapped trees
23+
24+
After preprocessing, the original problem is divided into two subproblems, time complexity: O(n)
25+
"""
26+
def flipEquiv2(self, root1, root2):
27+
def flip(root):
28+
if root:
29+
if root.left and root.right and root.left.val > root.right.val:
30+
root.left, root.right = root.right, root.left
31+
if not root.left:
32+
root.left, root.right = root.right, root.left
33+
flip(root.left)
34+
flip(root.right)
35+
36+
def is_equal(root1, root2):
37+
if not root1 or not root2:
38+
return root1 == root2
39+
return root1.val == root2.val and \
40+
is_equal(root1.left, root2.left) and \
41+
is_equal(root1.right, root2.right)
42+
43+
flip(root1)
44+
flip(root2)
45+
return is_equal(root1, root2)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Method 1: recursive in-order traversal
2+
def kthSmallest1(self, root, k):
3+
inorder = []
4+
def helper(root):
5+
if root:
6+
helper(root.left)
7+
inorder.append(root.val)
8+
helper(root.right)
9+
10+
helper(root)
11+
return inorder[k-1]
12+
13+
# Method 2: iterative in-order traversal
14+
def kthSmallest2(self, root, k):
15+
stack = []
16+
while root or stack:
17+
while root:
18+
stack.append(root)
19+
root = root.left
20+
root = stack.pop()
21+
k -= 1
22+
if k == 0: return root.val
23+
root = root.right
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# straight forward recursive solution
2+
3+
def lowestCommonAncestor(self, root, p, q):
4+
if not root: return None
5+
if root.val > p.val and root.val > q.val:
6+
return self.lowestCommonAncestor(root.left, p, q)
7+
elif root.val < p.val and root.val < q.val:
8+
return self.lowestCommonAncestor(root.right, p, q)
9+
return root
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# recursive solution: takes O(n) time
2+
# first get the height of the tree, then recusivly update the value
3+
4+
def printTree(self, root):
5+
def get_height(root):
6+
if not root: return 0
7+
return 1 + max(get_height(root.left), get_height(root.right))
8+
9+
def update(res, node, row, left, right):
10+
if not node: return
11+
mid = (left + right) // 2
12+
res[row][mid] = str(node.val)
13+
update(res, node.left, row + 1, left, mid - 1)
14+
update(res, node.right, row + 1, mid + 1, right)
15+
16+
height = get_height(root)
17+
width = 2 ** height - 1
18+
res = [['' for _ in range(width)] for _ in range(height)]
19+
update(res, root, 0, 0, width - 1)
20+
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
simple union find with path compression:
3+
at first, each vertices are disjoint, there are N connected components at the begining,
4+
after add each edge, we unify those two connected components, if two vertices are already
5+
in the same connected component, then this edge will form a circle, just return this edge
6+
"""
7+
8+
def findRedundantConnection(self, edges):
9+
id = list(range(len(edges) + 1))
10+
11+
def find(u):
12+
root = u
13+
while root != id[root]: root = id[root]
14+
15+
# path compression:
16+
while u != root:
17+
next = id[u]
18+
id[u] = root
19+
u = next
20+
21+
return root
22+
23+
for u, v in edges:
24+
root1, root2 = find(u), find(v)
25+
if root1 == root2: return [u, v]
26+
27+
# else, unify these two components:
28+
id[root1] = root2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
because of the special porperty of the tree, the question basically is asking to find
3+
the smallest element in the subtree of root. So, we can recursively find left and right
4+
value that is not equal to the root's value, and then return the smaller one of them
5+
"""
6+
def findSecondMinimumValue(self, root):
7+
if not root: return -1
8+
if not root.left and not root.right: return -1
9+
10+
left, right = root.left.val, root.right.val
11+
if left == root.val: left = self.findSecondMinimumValue(root.left)
12+
if right == root.val: right = self.findSecondMinimumValue(root.right)
13+
if left != -1 and right != -1: return min(left, right)
14+
if left == -1: return right
15+
if right == -1: return left
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""
2+
straight forward recursive solution:
3+
if left node is leave, add the value and the the right subtree
4+
if not, then recursively call left and right subtree
5+
"""
6+
def sumOfLeftLeaves(self, root):
7+
if not root: return 0
8+
if root.left and not root.left.left and not root.left.right:
9+
return root.left.val + self.sumOfLeftLeaves(root.right)
10+
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

0 commit comments

Comments
 (0)