给你二叉树的根结点 root
,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用
TreeNode
,其中right
子指针指向链表中下一个结点,而左子指针始终为null
。 - 展开后的单链表应该与二叉树 先序遍历 顺序相同。
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:
输入:root = []
输出:[]
# @lc app=leetcode.cn id=114 lang=python3
#
# [114] 二叉树展开为链表
#
# @lc code=start
# 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: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
nums=[]
def inorder(root):
if root==None:
return
nums.append(root)
inorder(root.left)
inorder(root.right)
if root==None:
return None
inorder(root)
root=nums[0]
lens=len(nums)
for i in range(lens-1):
print(nums[i].val)
nums[i].left = None
nums[i].right = nums[i+1]
nums[lens-1].left= None
nums[lens-1].right=None
return root
# @lc code=end