第六章 二叉树 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)
}
相关推荐
xqlily14 分钟前
Prover9/Mace4 的形式化语言简介
人工智能·算法
资深web全栈开发35 分钟前
二分搜索中 `right = mid` 而非 `right = mid + 1` 的解释
算法·rust·二分搜索
狮子也疯狂2 小时前
基于Django实现的智慧校园考试系统-自动组卷算法实现
python·算法·django
爱coding的橙子2 小时前
每日算法刷题Day84:11.11:leetcode 动态规划9道题,用时2h
算法·leetcode·动态规划
飞鱼&2 小时前
java数据结构
数据结构·二叉树·散列表·红黑树
shenghaide_jiahu2 小时前
字符串匹配和回文串类题目
学习·算法·动态规划
有意义3 小时前
为什么说数组是 JavaScript 开发者必须精通的数据结构?
前端·数据结构·算法
努力努力再努力wz3 小时前
【Linux进阶系列】:线程(下)
linux·运维·服务器·c语言·数据结构·c++·算法
rit84324993 小时前
瑞利信道下PSK水声通信系统均衡技术
算法
ValhallaCoder3 小时前
Day33-动态规划
数据结构·python·算法·动态规划