给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围 [0, 2000] 内
- -1000 <= Node.val <= 1000
解题:
func levelOrderBottom(root *TreeNode) [][]int {
var r [][]int
if root == nil {
return r
}
stack := []*TreeNode{root}
for len(stack) > 0 {
var arr []int
var p []*TreeNode
for len(stack) > 0 {
node := stack[0]
stack = stack[1:]
arr = append(arr, node.Val)
if node.Left != nil {
p = append(p, node.Left)
}
if node.Right != nil {
p = append(p, node.Right)
}
}
r = append(r, arr)
stack = p
}
l := len(r)
for i := 0; i < l/2; i++ {
r[i], r[l-i-1] = r[l-i-1], r[i]
}
return r
}
官方解答:
1.广度优先搜索
func levelOrderBottom(root *TreeNode) [][]int {
var levelOrder [][]int
if root == nil {
return levelOrder
}
queue := []*TreeNode{root}
for len(queue) > 0 {
var level []int
size := len(queue)
for i := 0; i < size; i++ {
node := queue[0]
queue = queue[1:]
level = append(level, node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
levelOrder = append(levelOrder, level)
}
for i := 0; i < len(levelOrder)/2; i++ {
levelOrder[i], levelOrder[len(levelOrder)-1-i] = levelOrder[len(levelOrder)-1-i], levelOrder[i]
}
return levelOrder
}