題目
原題頁面:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
題目型別:Tree, Depth-first Search
難度評價: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.
分析
題目的演算法本身並不難理解,按照先序遍歷的節點順序將一棵二叉樹拉平為一個“連結串列”。因此後序遍歷二叉樹,先將左子樹“拉平”,再將右子樹“拉平”,然後如果左子樹不是None,就將已經拉平為“連結串列”的左子樹,嵌入到當前節點與直接右孩子節點(可能右孩子是None)之間。關鍵在於一些分支上要判斷是否不為None,很容易出錯。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-flatten-binary-tree-to-linked-list/
