给你二叉树的根结点 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 = []
输出:[]
示例 3:输入:root = [0]
输出:[0]提示:
树中结点数在范围 [0, 2000] 内
-100 <= Node.val <= 100进阶:你可以使用原地算法(O(1) 额外空间)展开这棵树吗?
代码有官方的和自己写的,空间复杂度都是 O(1)O(1)O(1)
from 二叉树的层序遍历 import Solution as outs
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.
"""
if root is None:
return
if root.left is not None:
self.flatten(root.left)
p = root.right
root.right = root.left
root.left = None
q = root.right
while q is not None and q.right is not None:
q = q.right
q.right = p
if root.right is not None:
self.flatten(root.right)
#leetcode官方
def flatten(self, root: TreeNode) -> None:
curr = root
while curr:
if curr.left:
predecessor = nxt = curr.left
while predecessor.right:
predecessor = predecessor.right
predecessor.right = curr.right
curr.left = None
curr.right = nxt
curr = curr.right
if __name__ == '__main__':
s = Solution()
tt = outs()
#r = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(5, None, TreeNode(6)))
#r = TreeNode(0)
r = TreeNode(1, None, TreeNode(2, TreeNode(3)))
s.flatten(r)
print(tt.levelOrder(r))