Skip to content

Commit c6c84d9

Browse files
committed
no message
1 parent 895710d commit c6c84d9

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

problems/convert-binary-search-tree-to-sorted-doubly-linked-list.py

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,62 @@ def helper(node, hook_left=True):
4343
root.left = right_most
4444
right_most.right = root
4545

46-
return root
46+
return root
47+
48+
49+
50+
51+
52+
"""
53+
Time: O(N)
54+
Space: O(LogN) if the tree is balanced.
55+
56+
Do an inorder traversal and link the node.left to the prev and prev.right to node.
57+
"""
58+
class Solution(object):
59+
def treeToDoublyList(self, root):
60+
if not root: return root
61+
62+
stack = []
63+
node = root
64+
preHead = Node(-1)
65+
prev = preHead
66+
67+
while node or stack:
68+
while node:
69+
stack.append(node)
70+
node = node.left
71+
72+
node = stack.pop()
73+
74+
prev.right = node
75+
node.left = prev
76+
77+
prev = node
78+
79+
node = node.right
80+
81+
head = preHead.right
82+
head.left = prev
83+
prev.right = head
84+
85+
return head
86+
87+
"""
88+
FYI
89+
"""
90+
def inOrderTraverse(root):
91+
stack = []
92+
node = root
93+
94+
while node or stack:
95+
while node:
96+
stack.append(node)
97+
node = node.left
98+
99+
node = stack.pop()
100+
101+
#do something
102+
print node.val
103+
104+
node = node.right

problems/largest-bst-subtree.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Time: O(N) for recursively traverse each node once.
3+
Space: O(LogN) for recursive stack.
4+
"""
5+
class Solution(object):
6+
def largestBSTSubtree(self, root):
7+
def helper(node, minVal, maxVal):
8+
if not node: return True, 0, float('-inf'), float('inf')
9+
if not node.left and not node.right: return True, 1, node.val, node.val
10+
11+
isLeftBST, leftSize, leftMin, leftMax = helper(node.left, minVal, node.val)
12+
isRightBST, rightSize, rightMin, rightMax = helper(node.right, node.val, maxVal)
13+
14+
currMin = min(leftMin, rightMin, node.val)
15+
currMax = max(leftMax, rightMax, node.val)
16+
17+
if isLeftBST and isRightBST and leftMax<node.val and node.val<rightMin:
18+
return True, 1+leftSize+rightSize, currMin, currMax
19+
else:
20+
return False, max(leftSize, rightSize), currMin, currMax
21+
22+
return helper(root, float('-inf'), float('inf'))[1]

0 commit comments

Comments
 (0)