leetcode_flatten binary tree to linked list

Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.
(压平二叉树)

Example:

1. 递归

递归压平子树,然后将左子树放在右子树上,并将左子树置为None。然后找到叶子节点将原来的右子树连接在后面。具体实现过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class :
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return

if root.left:
self.flatten(root.left)
if root.right:
self.flatten(root.right)

# move the left tree to the right, set left to None
p_temp = root.right
root.right = root.left
root.left = None

# find the leaf and link the right tree
p_tail = root
while p_tail.right:
p_tail = p_tail.right
p_tail.right = p_temp

return