登录
  • #打卡
  • #打卡组队

Swift刷题打卡,不能再颓了

Ajay91
832
13
// 102. Binary Tree Level Order Traversal

// 3

// / \

// 9 20

// / \

// 15 7

func leverOrder(_ root: TreeNode?) -> [[Int]] {

var result = [[Int]]()

guard let root = root else {

return result

}

var queue = [TreeNode]()

queue.append(root)

while !queue.isEmpty {

let size = queue.count

var arr = [Int]()

for _ in 0..<size {

let cur = queue.removeFirst()

arr.append(cur.val)

if let left = cur.left {

queue.append(left)

}

if let right = cur.right {

queue.append(right)

}

}

result.append(arr)

}

return result

}

var n1 = TreeNode(3)

var n2 = TreeNode(9)

var n3 = TreeNode(20)

var n4 = TreeNode(15)

var n5 = TreeNode(17)

n1.left = n2

n1.right = n3

n3.left = n4

n3.right = n5

let ans = leverOrder(n1)

print(ans)
13条回复
热度排序

发表回复