心路历程:
二叉树问题先无脑想到递归遍历,一般都是深度优先。然后递归函数的参数基本上都是二叉树的结点,返回值可有可无、可多可少。
这道题一个直观的想法就是遍历之后把各个结点值保存起来,然后创建新的结点加到题目中的head上。
很明显这道题有复杂度更低的直接转换方法,但是我没想清楚该怎么做。
注意的点:
1、用递归对二叉树进行遍历,本质是遍历二叉树的结点,回溯是遍历二叉树的边。因为结点遍历完就保存了,不需要再‘恢复现场’。
2、注意需要先序遍历,就是先append再遍历左右子树
3、对链表、二叉树结点赋给其他变量后,其他变量是可以操作内存的。
解法:普通的二叉树遍历
# 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.
"""
res = []
def dfs(node):
if not node:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
if not res:
return
root1 = root # 这一行赋值只是为了证明节点赋值后的操作也可以改变原节点的内存组织
root1.left = None
root1.right = None
root1.val = res[0]
tmp = root1
# print(res)
for eve in res[1:]:
node = TreeNode(eve, None, None)
tmp.right = node
tmp = node