💪💪💪此系列仅为记录本人补充学习数据结构相关知识,有兴趣的,大家可以共同学习👏👏👏
注意!注意!注意!
二叉树数据结构的遍历方式
前序遍历:中 -> 左 -> 右
中序遍历:左 -> 中 -> 右
后序遍历:左-> 右 -> 中
[= 二叉树前序遍历 =]
题目描述
解题方法
// 遍历顺序:中->左->右
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := []int{root.Val}
res = append(res, preorderTraversal(root.Left)...)
res = append(res, preorderTraversal(root.Right)...)
return res
}
[= 二叉树中序遍历 =]
题目描述
解题方法
// 遍历顺序:左->中->右
func inorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := append(inorderTraversal(root.Left), root.Val)
res = append(res, inorderTraversal(root.Right)...)
return res
}
[= 二叉树后序遍历 =]
题目描述
解题方法
// 遍历顺序:左->右->中
func postorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := append(postorderTraversal(root.Left), postorderTraversal(root.Right)...)
res = append(res, root.Val)
return res
}