Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like: 1
\
2
\
3
\
4
\
5
\
6
Given
Solution:
Stack Solution:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return nothing, do it in place def flatten(self, root): if root == None: return stack = [] stack.append(root) while len(stack) > 0: actual = stack.pop(); if actual.right != None: stack.append(actual.right) if actual.left != None: stack.append(actual.left) if len(stack) > 0: actual.right = stack[len(stack)-1] actual.left = None
Inplace Solution:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return nothing, do it in place def flatten(self, root): while root != None: if root.left != None: pre = root.left while pre.right != None: pre = pre.right pre.right = root.right root.right = root.left root.left = None root = root.right
No comments :
Post a Comment