题目描述
请实现一个函数按照之字形顺序从上向下打印二叉树。
即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/ \
12 2
/ \
6 4
输出:[[8], [2, 12], [6, 4]]
C++ 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func printFromTopToBottom(root *TreeNode) [][]int {
if root == nil {
return nil
}
var ans [][]int
var a []int
//true 左右 false 右左
var turn = true
var temp = []*TreeNode{root,nil}
for{
if temp[0] != nil {
a = append(a,temp[0].Val)
if temp[0].Left != nil {
temp = append(temp,temp[0].Left)
}
if temp[0].Right != nil {
temp = append(temp,temp[0].Right)
}
}else{
//左-->右
if turn {
ans = append(ans,a)
turn = false
//右-->左
} else {
for i := 0 ; i < len(a)/2 ; i++ {
a[i],a[len(a)-1-i] = a[len(a)-1-i],a[i]
}
ans = append(ans,a)
turn = true
}
a = nil
if len(temp) == 1{
break
}else{
temp = append(temp,nil)
}
}
temp = temp[1:]
}
return ans
}