Skip to content

Commit c5b5c40

Browse files
committed
[feat] Add removeKDigits to make smallest number, insert in bstPreOrder
1 parent b58ad77 commit c5b5c40

File tree

2 files changed

+54
-10
lines changed

2 files changed

+54
-10
lines changed

platform-problems/leetcode/may-2020-leetcoding-challenge/13-LeetCode-removeKDigits.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,16 @@ def removeKdigits(self, num, k):
2121
numList = list(num)
2222
numList.sort()
2323
return numList[0]
24-
totalRemoved = 0
25-
numClone = num
26-
for i in range(len(num) - 1):
27-
if num[i] > num[i + 1]:
28-
numClone = numClone.replace(num[i], '', 1)
29-
totalRemoved += 1
30-
if totalRemoved == k:
31-
break
32-
return removeZeros(numClone[:len(numClone) - k + totalRemoved])
24+
25+
for j in range(k):
26+
i = 0
27+
while i + 1 < len(num) and num[i] <= num[i + 1]:
28+
i += 1
29+
# remove the character
30+
num = num[:i] + num[i + 1:]
31+
return removeZeros(num)
3332

3433

3534
if __name__ == '__main__':
3635
s = Solution()
37-
print(s.removeKdigits("1234567890", 9))
36+
print(s.removeKdigits("122519", 3))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'''
2+
Return the root node of a binary search tree that matches the given preorder traversal.
3+
4+
(Recall that a binary search tree is a binary tree where for every node, any descendant of node.
5+
left has a value < node.val, and any descendant of node.right has a value > node.val.
6+
Also recall that a preorder traversal displays the value of the node first,
7+
then traverses node.left, then traverses node.right.)
8+
9+
It's guaranteed that for the given test cases there is always possible to find a
10+
binary search tree with the given requirements.
11+
12+
Example 1: Input: [8,5,1,7,10,12], Output: [8,5,10,1,7,null,12]
13+
'''
14+
import math
15+
16+
# Definition for a binary tree node.
17+
# class TreeNode(object):
18+
# def __init__(self, val=0, left=None, right=None):
19+
# self.val = val
20+
# self.left = left
21+
# self.right = right
22+
23+
24+
def insertInBst(root, val):
25+
if root == None:
26+
root = TreeNode()
27+
root.val = val
28+
return root
29+
if val < root.val:
30+
root.left = insertInBst(root.left, val)
31+
if val > root.val:
32+
root.right = insertInBst(root.right, val)
33+
return root
34+
35+
36+
class Solution(object):
37+
def bstFromPreorder(self, preorder):
38+
"""
39+
:type preorder: List[int]
40+
:rtype: TreeNode
41+
"""
42+
root = None
43+
for i in range(len(preorder)):
44+
root = insertInBst(root, preorder[i])
45+
return root

0 commit comments

Comments
 (0)