题目
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
解题思路
自己的想法不是很清楚
看了大佬们的代码
还需要再回过头多看一下
每一层,都把右子树保存下来,再把左子树放在右子树上,再把左子树设为null,再把刚刚的右子树放在新的右子树的后面。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root is None:
return root
self.prev = root
self.flatten(root.left)
temp = root.right
root.right, root.left = root.left, None
self.prev.right = temp
self.flatten(temp)