题目:
给你二叉树的根结点
root
,请你将它展开为一个单链表:
- 展开后的单链表应该同样使用
TreeNode
,其中right
子指针指向链表中下一个结点,而左子指针始终为null
。- 展开后的单链表应该与二叉树 先序遍历 顺序相同。
来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
示例:
示例 1:
输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
示例 2:输入:root = []
输出:[]
示例 3:输入:root = [0]
输出:[0]
解法:
先序遍历保存节点,接着把root左结点置空,右结点依次连接保存的结点。
代码:
# 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. """ result = [] stack = [] point = root while point or stack: while point: stack.append(point) result.append(point) point = point.left point = stack.pop().right if len(result) > 1: for node in result[1:]: root.left = None root.right = node root = root.right