Skip to content

Commit f5ce16f

Browse files
committed
Flatten Binary Tree to Linked List
1 parent b07905b commit f5ce16f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
3+
4+
Given a binary tree, flatten it to a linked list in-place.
5+
6+
For example, given the following tree:
7+
8+
1
9+
/ \
10+
2 5
11+
/ \ \
12+
3 4 6
13+
The flattened tree should look like:
14+
15+
1
16+
\
17+
2
18+
\
19+
3
20+
\
21+
4
22+
\
23+
5
24+
\
25+
6
26+
"""
27+
# Definition for a binary tree node.
28+
# class TreeNode(object):
29+
# def __init__(self, x):
30+
# self.val = x
31+
# self.left = None
32+
# self.right = None
33+
34+
class Solution(object):
35+
def flatten(self, root):
36+
"""
37+
:type root: TreeNode
38+
:rtype: void Do not return anything, modify root in-place instead.
39+
"""
40+
node = root
41+
while node:
42+
if node.left:
43+
nodeL = node.left
44+
while nodeL.right:
45+
nodeL = nodeL.right
46+
tmp, node.left = node.left, None
47+
nodeL.right, node.right = node.right, tmp
48+
node = node.right

0 commit comments

Comments
 (0)