The difference between pre-order, in-order, and post-order is: the position of the root node, the root node is in the front, that is the pre-order, the root node is in the middle, that is the in-order, and the root node is in the back, that is the post-order.
Layer order traversal: The binary tree is traversed layer by layer.
preorder traversal
The specific process is as follows:
first visit the root node, then visit the left and right nodes, if the left node is still below, then visit the left node of the left node, and then visit the right node under the left node. and so on.
code show as below:
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if node is None:
return
ans.append(node.val) # 先访问根节点
dfs(node.left) # 再访问左节点
dfs(node.right) # 再访问右侧节点
dfs(root)
return ans
Inorder traversal
In the case of in-order traversal, first visit the left node, then visit the root node, and then visit the right node (put the root node in the middle.)
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if node is None:
return
dfs(node.left) #先访问左节点
ans.append(node.val) #再访问根节点
dfs(node.right) # 再访问右侧节点
dfs(root)
return ans
post order traversal
Post-order traversal starts with the left node, then the right node, and then the root node (the root node is placed at the end for access)
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if node is None:
return
dfs(node.left) # 先左节点
dfs(node.right) # 再右侧节点
ans.append(node.val) # 最后根节点
dfs(root)
return ans
sequence traversal
Traversed layer by layer
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = []
stack = [root] if root else [] # 保存根节点
while stack:
nex = [] # 临时存放中间节点
ans.append([node.val for node in stack]) #输出根节点的值
for node in stack: # 依次访问根节点的左右
if node.left:
nex.append(node.left) #将中间节点临时存放起来,
if node.right:
nex.append(node.right)
stack = nex 将中间结果视为根节点,重新再来
return ans
Level order traversal of N-ary tree
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return []
res=[]
q=[root]
while q:
res.append([i.val for i in q])
for i in range(len(q)):
node=q.pop(0)
for j in node.children:
q.append(j)
return res