第六章 二叉树 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)
}
相关推荐
一只齐刘海的猫2 分钟前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏11125 分钟前
数据结构 | 八大排序
数据结构·算法·排序算法
liulilittle1 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy1 小时前
【算法五十七】146. LRU 缓存
算法·缓存
Irissgwe2 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白2 小时前
数据容器集合set/frozenset
数据结构
凌波粒2 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle2 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂2 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠3 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法