Skip to content

Instantly share code, notes, and snippets.

@izeigerman
Created May 23, 2019 15:39
Show Gist options
  • Save izeigerman/c7f9a2ebfcef3b4662e651f7931d1584 to your computer and use it in GitHub Desktop.
Save izeigerman/c7f9a2ebfcef3b4662e651f7931d1584 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def _helper(self, tree_root):
this_node = Node(tree_root.val)
if tree_root.left is not None:
left_head, left_tail = self._helper(tree_root.left)
head = left_head
left_tail.right = this_node
this_node.left = left_tail
else:
head = this_node
if tree_root.right is not None:
right_head, right_tail = self._helper(tree_root.right)
tail = right_tail
right_head.left = this_node
this_node.right = right_head
else:
tail = this_node
return head, tail
def treeToDoublyList(self, root):
head, tail = self._helper(root)
head.left = tail
tail.right = head
return head
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment