Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created October 3, 2015 12:10
Show Gist options
  • Select an option

  • Save viveksyngh/88451010f1677f88bbc9 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/88451010f1677f88bbc9 to your computer and use it in GitHub Desktop.
Given a binary tree, flatten it to a linked list in-place.
__author__ = 'Vivek'
#Given a binary tree, flatten it to a linked list in-place.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return the root node in the tree
def rightMost(self, x) :
p = x
while p.right != None :
p = p.right
return p
def helper(self, root) :
if root == None :
return root
if root.left and root.right :
x = self.helper(root.left)
rm = self.rightMost(x)
y = self.helper(root.right)
root.left = None
root.right = x
rm.right = y
rm.left = None
elif root.left :
x = self.helper(root.left)
root.left = None
root.right = x
else :
x = self.helper(root.right)
root.left = None
root.right = x
return root
def flatten(self, A):
if A == None :
return None
else :
return self.helper(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment