This is much more complex than the last problem. The thought is to go '.next' to see if there is any link that needed to be built, and the key is to determine next recursion position.
Solution:
# T:O(n) S:O(1)
class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
head = root
while head:
prev, cur, next_head = None, head, None
while cur:
if next_head is None:
if cur.left:
next_head = cur.left
elif cur.right:
next_head = cur.right
if cur.left:
if prev:
prev.next = cur.left
prev = cur.left
if cur.right:
if prev:
prev.next = cur.right
prev = cur.right
cur = cur.next
head = next_head
Run Time: 156 ms
No comments:
Post a Comment