第六章 二叉树 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)
}
相关推荐
welkin5 分钟前
KMP 个人理解
前端·算法
半桔11 分钟前
红黑树剖析
c语言·开发语言·数据结构·c++·后端·算法
eason_fan20 分钟前
前端面试手撕代码(字节)
前端·算法·面试
今天_也很困27 分钟前
牛客2025年愚人节比赛
c++·算法
Joe_Wang529 分钟前
[图论]拓扑排序
数据结构·c++·算法·leetcode·图论·拓扑排序
2401_858286111 小时前
CD21.【C++ Dev】类和对象(12) 流插入运算符的重载
开发语言·c++·算法·类和对象·运算符重载
梭七y1 小时前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
月亮被咬碎成星星1 小时前
LeetCode[383]赎金信
算法·leetcode
嘉友2 小时前
Redis zset数据结构以及时间复杂度总结(源码)
数据结构·数据库·redis·后端
无难事者若执2 小时前
新手村:逻辑回归-理解03:逻辑回归中的最大似然函数
算法·机器学习·逻辑回归