1、先完成了前序遍历:144. 二叉树的前序遍历
【根左右】
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return None
nodelist=[]
self.dfs(root,nodelist)
return nodelist
def dfs(self, root: TreeNode,nodelist):
if not root: #叶子节点的左右为None,会直接返回
return
nodelist.append(root.val)
self.dfs(root.left,nodelist)
self.dfs(root.right,nodelist)
11-18前序遍历的堆栈法:
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res=[]
if root is None:
return res
node=root
stack=[]
while node or stack:
while node:
res.append(node.val)
stack.append(node)
node=node.left #向左走
node=stack.pop() #返回头节点
node=node.right #取右边
return res
2、把取出来的值,重构成树的结构。左子树为None,右子树为下一节点。注意size的范围(节点的是0~size-1, 叶子是1~size)。
# 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.
"""
if not root:
return None
nodelist=[]
self.dfs(root,nodelist)
size=len(nodelist)
size=size-1
i=0
while size:
nod=nodelist[i]
nod.left=None
nod.right=nodelist[i+1]
i=i+1
size=size-1
def dfs(self, root: TreeNode,nodelist):
if not root:
return
nodelist.append(root)
self.dfs(root.left,nodelist)
self.dfs(root.right,nodelist)