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

求二叉树的层序遍历

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 {
	if root == nil {
		return [][]int{}
	}

	var q []*TreeNode
	var n *TreeNode
	var idx = 0
	q = append(q, root)
	var res [][]int

	for len(q) != 0 {
		res = append(res, []int{})
		qLen := len(q)
		for i := 0; i < qLen; i++ {
			n, q = q[0], q[1:]
			res[idx] = append(res[idx], n.Val)
			if n.Left != nil {
				q = append(q, n.Left)
			}
			if n.Right != nil {
				q = append(q, n.Right)
			}
		}
		idx++
	}
	return res
}

全部评论

相关推荐

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