题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
思路:层序遍历后得到的二维切片,分层进行逆序输出即可。
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pRoot TreeNode类
* @return int整型二维数组
*/
func Print(pRoot *TreeNode) [][]int {
// write code here
//层序遍历
LevelOrderSlice := levelOrder(pRoot)
for i := 0; i < len(LevelOrderSlice); i++ {
//需要进行变化“之”字形的层数,逆序即可
if i%2 != 0 {
reverse(LevelOrderSlice[i])
}
}
return LevelOrderSlice
}
//反转切片元素输出
func reverse(s []int) []int {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
//层序遍历
func levelOrder(root *TreeNode) [][]int {
result := make([][]int, 0)
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, level int) {
if node == nil {
return
}
if level == len(result) {
result = append(result, []int{})
}
result[level] = append(result[level], node.Val)
dfs(node.Left, level+1)
dfs(node.Right, level+1)
}
dfs(root, 0)
return result
}