题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

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
    if pRoot == nil {
        return [][]int{}
    }
    queue := []*TreeNode{pRoot}
    var floors [][]int 
    flag := 1
    for len(queue) > 0 {
        l := len(queue) 
        
        floor := make([]int,l)
        for i:=0;i<l;i++{
            root := queue[0]
            queue = queue[1:]
            if flag == 1 {
                floor[i] = root.Val
            }else{
                 floor[l-1-i] = root.Val
            }
            
            
            if root.Left != nil {
                queue = append(queue,root.Left)
            }
            if root.Right != nil {
                queue = append(queue,root.Right)
            }
        }
        floors = append(floors,floor)
        flag *= -1
    }
    return floors
}
全部评论

相关推荐

草稿猫编程:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务