Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created September 14, 2018 03:18
Show Gist options
  • Select an option

  • Save yokolet/cda7ca19a030b39300619568df03de23 to your computer and use it in GitHub Desktop.

Select an option

Save yokolet/cda7ca19a030b39300619568df03de23 to your computer and use it in GitHub Desktop.
Flatten Binary Tree to Linked List
"""
Description:
Given a binary tree, flatten it to a linked list in-place.
Example:
Input:
1
/ \
2 5
/\ \
3 4 6
Output:
1
\
2
\
3
\
4
\
5
\
6
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def flatten(root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
stack = [root]
prev = None
while stack:
cur = stack.pop()
if prev:
prev.right = cur
prev.left = None
prev = cur
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment