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

按之字形顺序打印二叉树

https://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 {
	list := make([]*TreeNode, 0)
	res := make([][]int, 0)
	if pRoot == nil {
		return res 
	}
	list = append(list, pRoot)
	for i := 0; len(list) > 0; i++ {
		tmpList := make([]*TreeNode, 0)
		for _, node := range list {
			if node.Left != nil {
				tmpList = append(tmpList, node.Left)
			}
			if node.Right != nil {
				tmpList = append(tmpList, node.Right)
			}
		}
		a := make([]int, 0)
		if i&1 == 0 {
			for _, node := range list {
				a = append(a, node.Val)
			}
		} else {
			for j := len(list) - 1; j >= 0; j-- {
				a = append(a, list[j].Val)
			}
		}
		res = append(res, a)
		list = tmpList
	}
	return res
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务