1. What I learned
Can’t use only ‘return’ in Ternary Operator
In the Ternary Operator, only the ‘return’ statement cannot be used.
print('H') if A else return
#There's an error
2. How I sloved
I used Tree and DFS to solve this problem. The input values came in order. So I went on to get the middle value of the values and split the list in two and repeated this process to create a tree. When making the tree, I used the binary tree concept to send a small value to the left and a large value to the right.
3. Code
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def getValues(head):
temp = []
while head:
temp.append(head.val)
head = head.next
return temp
def makeTree(values,low,high):
if low>high:
return
mid = (low+high)//2
new_node = TreeNode(values[mid])
new_node.left = makeTree(values,low,mid-1)
new_node.right = makeTree(values,mid+1,high)
return new_node
value_list = getValues(head)
root = makeTree(value_list,0,len(value_list)-1)
return root
4. Result
Runtime : 128 ms(83.86%), Memory usage : 20.1 MB(58.06%)
(Runtime can be different by a system even if it is a same code.)