文章目录
一、二叉树的中序遍历
题目:给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
1、递归法(推荐)
很简单,就不说后序和前序了!
# 中序遍历为例
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# 法1: 递归
res = []
self.inorder(root, res)
return res
def inorder(self, root, res):
if root:
self.inorder(root.left, res)
res.append(root.val)
self.inorder(root.right, res)
2、迭代法(了解)—中序遍历
# 中序遍历
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# 法2: 迭代-->栈
res, stack = [], []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
temp = stack.pop()
res.append(temp.val)
root = node.right
return res
3、迭代法(了解)—前序遍历
# 后序遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res, stack = [], []
while stack or root:
if root:
stack.append(root)
res.append(root.val)
root = root.left
else:
temp = stack.pop()
root = temp.right
return res
4、迭代法(了解)—后序遍历
# 后序遍历
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
# 用前序遍历的思想做后序遍历
res, stack = [], []
while stack or root:
if root:
res.append(root.val)
stack.append(root)
root = root.right
else:
temp = stack.pop()
root = temp.left
# 上面是根、右、左遍历。res翻转就得到了左右根
return res[::-1]
二、N叉树的遍历
N叉树只有前序、后序遍历!无中序遍历
前序遍历:根的值在其他所有子节点之前输出
后序遍历:根的值在其他所有子节点之后输出
1、递归法(推荐)
class Solution(object):
def preorder(self, root):
res =[]
self.dfs(root, res)
return res
def dfs(self, root, res):
if root:
res.append(root.val) # 后序遍历就是把这句放到最后
for child in root.children:
self.dfs(child, res)
return res
2、迭代法(了解)
# 前序遍历
class Solution(object):
def preorder(self, root):
if not root: return []
stack, res = [root], []
while stack:
temp = stack.pop()
res.append(temp.val)
stack.extend(temp.children[::-1])
return res
# 后序遍历 --- 其实还是借用的前序遍历的思想
class Solution(object):
def postorder(self, root):
if not root: return []
stack, res = [root], []
while stack:
temp = stack.pop()
res.append(temp.val)
stack.extend(temp.children)
return res[::-1]
三、二叉树及N叉树的层序遍历(广度优先遍历)
N叉树层序遍历
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
queue, res = [root], []
while queue and root:
temp = []
for _ in range(len(queue)):
node = queue.pop(0)
temp.append(node.val)
queue.extend(node.children)
res.append(temp)
return res
二叉树的层序遍历
import collections
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
queue, res = [root], []
while queue and root:
tmp = []
for _ in range(len(queue)):
node = queue.pop(0)
tmp.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(tmp)
return res