简繁EN

LeetCodeNo. 131

【LeetCode with Python】 114. Flatten Binary Tree to Linked List

目錄

題目

原題頁面: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 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.


分析

題目的演算法本身並不難理解,按照先序遍歷的節點順序將一棵二叉樹拉平為一個“連結串列”。因此後序遍歷二叉樹,先將左子樹“拉平”,再將右子樹“拉平”,然後如果左子樹不是None,就將已經拉平為“連結串列”的左子樹,嵌入到當前節點與直接右孩子節點(可能右孩子是None)之間。關鍵在於一些分支上要判斷是否不為None,很容易出錯。


程式碼

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

本文地址:https://xnerv.wang/zh-tw/leetcode-flatten-binary-tree-to-linked-list/