- Flatten Binary Tree to Linked List
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
click to show hints.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
my thoughts:
1. dfs recursion.
my solution:
**********44ms
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
def findList(root):
if not root:
return [None, None]
if not root.left and not root.right:
return [root, root]
if not root.left:
return [root, findList(root.right)[1]]
if not root.right:
left = findList(root.left)
root.right = root.left
root.left = None
return [root, left[1]]
left = findList(root.left)
right = findList(root.right)
root.left = None
root.right = left[0]
left[1].right = right[0]
return [root, right[1]]
findList(root)
my comments:
from other ppl's solution:
1. better recursion:
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}