102. 二叉树的层序遍历
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3/ \9 20/ \15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
code
- 二叉树的层次遍历 II ,把102题的结果反转输出
var res [][]intfunc levelOrder(root *TreeNode) [][]int {res = [][]int{}dfs(root, 0)return res
}func dfs(root *TreeNode, level int) {if root != nil {if len(res) == level {res = append(res, []int{})}res[level] = append(res[level], root.Val)dfs(root.Left, level+1)dfs(root.Right, level+1)}
}
Code
var res [][]int
func dfs(root *TreeNode, level int) {if root != nil {if len(res) == level {res = append(res, nil)}res[level] = append(res[level], root.Val)dfs(root.Left, level+1)dfs(root.Right, level+1)}}func reverse(res [][]int) [][] int {long := len(res)-1i := 0for long > i {res[long], res[i] = res[i], res[long]long--i++}return res
}func levelOrderBottom(root *TreeNode) [][]int {res = [][]int{}dfs(root, 0)reverse(res)return res
}