Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 01944f8

Browse files
python: add problem 109 and unittest
1 parent 0e8efb0 commit 01944f8

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

Python/sln_101_200/solution_101_110.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
import math
33
from typing import List
4+
from common_utils import ListNode
45

56

67
class TreeNode:
@@ -108,6 +109,36 @@ def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
108109
:return:
109110
"""
110111

112+
def sortedListToBST(self, head: ListNode) -> TreeNode:
113+
"""
114+
109
115+
:param head:
116+
:return:
117+
"""
118+
if not head:
119+
return None
120+
mid_node = self.get_mid(head)
121+
mid = TreeNode(mid_node.val)
122+
123+
if mid_node == head:
124+
return mid
125+
126+
mid.left = self.sortedListToBST(head)
127+
mid.right = self.sortedListToBST(mid_node.next)
128+
return mid
129+
130+
def get_mid(self, head:ListNode):
131+
prev_ptr = None
132+
slow_node = fast_node = head
133+
134+
while fast_node and fast_node.next:
135+
prev_ptr = slow_node
136+
slow_node = slow_node.next
137+
fast_node = fast_node.next.next
138+
if prev_ptr:
139+
prev_ptr.next = None
140+
return slow_node
141+
111142
def isBalanced(self, root: TreeNode) -> bool:
112143
"""
113144
110

Python/sln_101_200/test_solution_101_110.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from unittest import TestCase
33
from sln_101_200.solution_101_110 import Solution_101_110, TreeNode
4-
from common_utils import build_binary_tree
4+
from common_utils import build_binary_tree,build_linked_list
55

66

77
class TestSolution_101_110(TestCase):
@@ -26,3 +26,7 @@ def test_maxDepth(self):
2626
def test_zigzagLevelOrder(self):
2727
tree = build_binary_tree([3, 9, 20, None, None, 15, 7])
2828
self.assertEqual(self.sln.zigzagLevelOrder(tree), [[3], [20, 9], [15, 7]])
29+
30+
def test_sortedListToBST(self):
31+
head = build_linked_list([-10,-3,0,5,9])
32+
root = self.sln.sortedListToBST(head)

0 commit comments

Comments
 (0)