中序遍历 迭代:
class Solution(object):
def inorderTraversal(self, root):
# 中序:左根右
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
stack = []
while stack or root:
# 不断往左子树方向走,每走一次就将当前节点保存到栈中,将左子节点压入栈
# 这是模拟递归的调用
if root:
stack.append(root)
root = root.left
# 当前节点为空,说明左边走到头了
# 出栈:左根右
# 将左子节点依次出栈,保存节点值,然后转向右边节点,继续上面整个过程
else:
tmp = stack.pop()
res.append(tmp.val)
root = tmp.right
return res
中序遍历 递归
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
def dfs(cur):
if not cur:
return
# 前序递归
res.append(cur.val)
dfs(cur.left)
dfs(cur.right)
# # 中序递归
# dfs(cur.left)
# res.append(cur.val)
# dfs(cur.right)
# # 后序递归
# dfs(cur.left)
# dfs(cur.right)
# res.append(cur.val)
res = []
dfs(root)
return res