题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

package main
import . "nc_tools"
/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return int整型二维数组
*/
func levelOrder(root *TreeNode) [][]int {
	var res [][]int
	if root == nil {
		return res 
	}
	nodeList := make([]*TreeNode, 0)
	nodeList = append(nodeList, root)
	for len(nodeList) > 0 {
		var next []*TreeNode
		var data []int
		for _, node := range nodeList {
			data = append(data, node.Val)
			if node.Left != nil {
				next = append(next, node.Left)
			}
			if node.Right != nil {
				next = append(next, node.Right)
			}
		}
		nodeList = next
		res = append(res, data)
	}
	return res
}

全部评论

相关推荐

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