中序遍历
classSolution:definorderTraversal(self, root: TreeNode)-> List[int]:
res =[]
stack =[]
cur = root
# 中序,模板:先用指针找到每颗子树的最左下角,然后进行进出栈操作while stack or cur:while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
前序遍历
classSolution:defpreorderTraversal(self, root: TreeNode)-> List[int]:
res =[]
stack =[]
cur = root
while stack or cur:while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.left
cur = stack.pop()
cur = cur.right
return res
后序遍历
classSolution:defpostorderTraversal(self, root: TreeNode)-> List[int]:
res =[]
stack =[]
cur = root
while stack or cur:while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.right
cur = stack.pop()
cur = cur.left
return res[::-1]