In [2]:
1
from binarytree import Node, build

114. Flatten Binary Tree to Linked List

2 step solution

  1. [cur, cur.left, cur.right] order traversal to store the right linked list.
  2. flatten given tree from root by using the stored list.
Let $ V $ be $n$, the time complexity is $O(n)$
In [3]:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def flatten(self, root: Node) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        order = []
        def func(cur:Node):
            if not cur:
                return
            order.append(cur)
            func(cur.left)
            func(cur.right)
        func(root)
        now = order[0]
        for x in order[1:]:
            now.right = x
            now.left = None
            now = now.right
sol = Solution()
In [6]:
1
2
3
4
5
6
null = None
A = [1,2,5,3,4,null,6]
root = build(A)
root.pprint()
sol.flatten(root)
root.pprint()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    __1
   /   \
  2     5
 / \     \
3   4     6


1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6


Leave a comment