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 6The flattened tree should look like:
1
2
3
4
5
6
7
8
9
10
11 1
\
2
\
3
\
4
\
5
\
6Hints:
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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-flatten-binary-tree-to-linked-list/
