首页 > 每天刷一道牛客题霸-第7天-合并有序链表
头像
菜鸟也要飞的高
编辑于 2020-12-04 12:28
+ 关注

每天刷一道牛客题霸-第7天-合并有序链表

题目

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3?tpId=190&&tqId=35337&rp=1&ru=/activity/oj&qru=/ta/job-code-high-rd/question-ranking

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 result [][]int
    if root == nil {
         return result
    }
    var queueFather []*TreeNode
    var queueChild []*TreeNode
    queueFather = append(queueFather,root)
    for len(queueFather) != 0 || len(queueChild) != 0 {
        var queue []int
        for len(queueFather) != 0 {
            item := queueFather[0]
            queue = append(queue, item.Val)
            queueFather = queueFather[1:]
            if item.Left != nil {
                queueChild = append(queueChild, item.Left)
            }
            if item.Right != nil {
                queueChild = append(queueChild, item.Right)
            }
        }
        result = append(result, queue)
        queue = []int{}
        for len(queueChild) != 0 {
            item := queueChild[0]
            queue = append(queue, item.Val)
            queueChild = queueChild[1:]
            if item.Left != nil {
                queueFather = append(queueFather,item.Left)
            }
            if item.Right != nil {
                queueFather = append(queueFather,item.Right)
            }
        }
        if len(queue) != 0{
            result = append(result, queue)
        }
    }
    return result
    // write code here
}

全部评论

(0) 回帖
加载中...
话题 回帖

相关热帖

近期热帖

近期精华帖

热门推荐