二叉树层序遍历登场!
-
- 二叉树的层序遍历
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一下就是从底开始倒序
-
- 二叉树的层序遍历 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)
}