方法1:递归 先序遍历
先设置一个列表preorderlist,用来存储先序遍历的结果
然后先序遍历
然后,一次扫描,建立链表。
# 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.
"""
#先序遍历
preorderlist = list()
def preorderTreversal(root):
if root:
preorderlist.append(root)
preorderTreversal(root.left)
preorderTreversal(root.right)
preorderTreversal(root)
size = len(preorderlist)
for i in range(1,size):
prev,curr = preorderlist[i - 1],preorderlist[i]
prev.left = None
prev.right = curr
迭代
# 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.
"""
#迭代
preorderlist = []
stack = []
node = root
while node or stack:
while node:
preorderlist.append(node)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
size = len(preorderlist)
for i in range(1,size):
prev,curr = preorderlist[i - 1],preorderlist[i]
prev.left = None
prev.right = curr
方法2:先序遍历的迭代法
如果仔细琢磨,发现方法1并不是原地
思路:
1、让root的左子树放到root的右子树处,
2、把root的原来的右子树放到root原左子树的最右结点处
3、更新root:root = root.right
具体的:
循环:
如果root没有左节点:
直接让root往右节点走,也就考虑root的下一个节点
否则:
找左子树的最右结点pre
让右子树挂到pre处
让左子树插入到右子树
令原左节点为空
更新root
python代码如下:
# 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.
"""
#迭代
while root:
if root.left == None:
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:
时间复杂度:O(N),N为结点数
空间复杂度:O(N)
方法2:
时间复杂度:O(N)
空间复杂度:O(1)