简繁EN

LeetCodeNo. 131

[LeetCode with Python] 114. Flatten Binary Tree to Linked List

Contents

Problem

Problem page: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Topics: Tree, Depth-first Search
Difficulty: Medium

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

1
2
3
4
5
    1
/ \
2 5
/ \ \
3 4 6

The flattened tree should look like:

1
2
3
4
5
6
7
8
9
10
11
1
\
2
\
3
\
4
\
5
\
6

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


Analysis

The algorithm itself isn't hard to understand. The idea is to flatten a binary tree into a "linked list" with the nodes in pre-order traversal order. So I use a post-order traversal: first I "flatten" the left subtree, then I "flatten" the right subtree. If the left subtree isn't None, I splice it, now a "linked list", between the current node and its immediate right child (which might be None). The tricky part is checking for non-None values in some of the branches. It's easy to get those checks wrong.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
if None == root:
return
if None != root.left:
self.flatten(root.left)
if None != root.right:
self.flatten(root.right)
left = root.left
right = root.left
while None != right and None != right.right:
right = right.right

if None != right:
right.right = root.right
if None != left: ###
root.right = left
root.left = None

Article link: https://xnerv.wang/en/leetcode-flatten-binary-tree-to-linked-list/