第六章 二叉树 part02

二叉树层序遍历登场!

    1. 二叉树的层序遍历
go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
 var q []*TreeNode
var head int
var tail int

func init() {
	q = make([]*TreeNode, 10010)
	head = -1
	tail = -1
}
func empty() bool {
	return head == tail
}
func push(x *TreeNode) {
	tail++
	q[tail] = x
}
func pop() *TreeNode {
	head++
	return q[head]
}
func size() int {
	return tail - head
}
func levelOrder(root *TreeNode) [][]int {
	var res [][]int
	
	push(root)
	for !empty() {
		qSize := size() // 细节
		var temp []int
		for i := 0; i < qSize; i++ {
			node := pop()
			if node == nil {
				continue
			}
			// watch
			temp = append(temp, node.Val)
			push(node.Left)
			push(node.Right)
		}
		if len(temp) > 0 {
			res = append(res, temp)
		}
	}
	return res
}

把结果数组reverse一下就是从底开始倒序

    1. 二叉树的层序遍历 II
go 复制代码
	slices.Reverse(res)
	return res

226.翻转二叉树

go 复制代码
func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    left := invertTree(root.Left)
    right :=invertTree(root.Right)
    root.Left = right
    root.Right = left
    return root
}

101. 对称二叉树

  • 后序遍历,但是一边要反后序遍历(一个左右,一个右左)
go 复制代码
func check (left, right *TreeNode) bool{
    if left == nil && right == nil {
        return true
    } 
    if (left == nil && right != nil) || (left != nil && right == nil) {
        return false
    }
    if left.Val != right.Val {
        return false
    }
    return check(left.Left, right.Right) && check(left.Right, right.Left)
 }
func isSymmetric(root *TreeNode) bool {
    return check(root.Left, root.Right)
}
相关推荐
syzyc11 分钟前
[ABC267F] Exactly K Steps
数据结构·动态规划·题解
向阳逐梦1 小时前
PID控制算法理论学习基础——单级PID控制
人工智能·算法
2zcode1 小时前
基于Matlab多特征融合的可视化指纹识别系统
人工智能·算法·matlab
Owen_Q1 小时前
Leetcode百题斩-二分搜索
算法·leetcode·职场和发展
矢志航天的阿洪2 小时前
蒙特卡洛树搜索方法实践
算法
草莓熊Lotso2 小时前
【数据结构初阶】--顺序表(二)
c语言·数据结构·经验分享·其他
汤姆爱耗儿药2 小时前
数据结构——散列表
数据结构·散列表
UnderTheTime2 小时前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_2 小时前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹2 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划