-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0114_flatten_binary_tree.py
More file actions
74 lines (64 loc) · 1.69 KB
/
0114_flatten_binary_tree.py
File metadata and controls
74 lines (64 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#------------------------------------------------------------------------------
# Question:
#------------------------------------------------------------------------------
# tags: #tree
'''
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root is None:
return
s = [root]
cur = None
while s:
n = s.pop()
if n:
s.append(n.right)
s.append(n.left)
if not cur:
cur = n
else:
cur.right = n
cur.left = None
cur = cur.right
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution(unittest.TestCase):
def test_simple(self):
s = Solution()
self.assertEqual(True, True)
unittest.main(verbosity=2)