# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
# 思路是先把右子树放到左子树最右边的节点上,然后把左子树放到右子树上,接着移到下一个节点
while root:
if not root.left:
root=root.right
else:
pre=root.left
while pre.right:
pre=pre.right
pre.right=root.right
root.right=root.left
root.left=None
root=root.right
思路:
1
/ \
2 5
/ \ \
3 4 6
//将 1 的左子树插入到右子树的地方
1
\
2 5
/ \ \
3 4 6
//将原来的右子树接到左子树的最右边节点
1
\
2
/ \
3 4
\
5
\
6
//将 2 的左子树插入到右子树的地方
1
\
2
\
3 4
\
5
\
6
//将原来的右子树接到左子树的最右边节点
1
\
2
\
3
\
4
\
5
\
6
这道题使用了二叉树的离断方法,然后再接上,然后用遍历每一个节点的方法,把整颗二叉树变成了链表