![c50f9f3b4d81c8908bf6a2079544747a.png](https://i-blog.csdnimg.cn/blog_migrate/e1f8b6658251a7d92ec38d30d66b9ec3.jpeg)
1. 前序遍历:
144. 二叉树的前序遍历
![6a9db7c40b8ff5ac2c06db1609af726a.png](https://i-blog.csdnimg.cn/blog_migrate/2fd3ddddf4f36989f9edd661715daa80.png)
递归
def preorderTraversal(self, root):
res=[]
def helper(root):
if not root:
return
res.append(root.val)
helper(root.left)
helper(root.right)
helper(root)
return res
迭代
def preorderTraversal(self, root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
#因为栈的逻辑是先进后出,因此先将右子树放入
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
2. 中序遍历
94. 二叉树的中序遍历
![4837fd13c96bc3a2ecb71a4fc0d9d0e6.png](https://i-blog.csdnimg.cn/blog_migrate/61f5ff9c91281b784dd7eb5d123029a9.png)
递归
def inorderTraversal(self, root):
res = []
def helper(root):
if not root:
return []
helper(root.left)
res.append(root.val)
helper(root.right)
helper(root)
return res
迭代
def inorderTraversal(self, root):
res, stack = [], []
while stack or root:
if root:
stack.append(root)
root=root.left
else:
node = stack.pop()
res.append(node.val)
root = node.right
return res
3. 后序遍历
145. 二叉树的后序遍历
![b9327efa6a2290293656e6aec9b18617.png](https://i-blog.csdnimg.cn/blog_migrate/da4480496f6c5f193f49952ea3fbfa1e.png)
递归
def inorderTraversal(self, root):
res = []
def helper(root):
if not root:
return []
helper(root.left)
helper(root.right)
res.append(root.val)
helper(root)
return res
迭代
def preorderTraversal(self, root):
if not root:
return []
res = []
stack = [root]
while stack:
node = stack.pop()
res.append(node.val)
#此处和前序遍历不同,现将左子树压入栈中
if node.right:
stack.append(node.left)
if node.left:
stack.append(node.right)
#倒序输出
return res[::-1]
4. 层次遍历
![188a9574b813c7917a21cb0083f7deab.png](https://i-blog.csdnimg.cn/blog_migrate/9f9dfe3a0b38424ac784da2f860fd7ca.png)
自上而下层次遍历(广度优先法)
102. 二叉树的层序遍历
def levelOrder(self, root):
if not root:
return []
res = []
queue = [root]
while queue:
size =len(queue)
temp =[]
for _ in range(size):
node = queue.pop(0)
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
return res
自下而上层次遍历
107. 二叉树的层次遍历 II
def levelOrderBottom(self, root):
if not root:
return []
res = []
queue = [root]
while queue:
size =len(queue)
temp =[]
for _ in range(size):
node = queue.pop(0)
temp.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(temp)
#将自上而下的层次遍历倒序输出
return res[::-1]