-
-
Save tangqiaoboy/a7d24ac5ca266d650aaa91615f39ffae to your computer and use it in GitHub Desktop.
iOS 面试题(12):按层遍历二叉树的节点
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Binary Tree Level Order Traversal.swift | |
// | |
// Created by Tang Qiao. | |
// | |
import Foundation | |
private class TreeNode { | |
public var val: Int | |
public var left: TreeNode? | |
public var right: TreeNode? | |
public init(_ val: Int) { | |
self.val = val | |
self.left = nil | |
self.right = nil | |
} | |
} | |
private class Solution { | |
func levelOrder(_ root: TreeNode?) -> [[Int]] { | |
guard let root = root else { | |
return [] | |
} | |
var result = [[TreeNode]]() | |
var level = [TreeNode]() | |
level.append(root) | |
while level.count != 0 { | |
result.append(level) | |
var nextLevel = [TreeNode]() | |
for node in level { | |
if let leftNode = node.left { | |
nextLevel.append(leftNode) | |
} | |
if let rightNode = node.right { | |
nextLevel.append(rightNode) | |
} | |
} | |
level = nextLevel | |
} | |
let ans = result.map { $0.map { $0.val }} | |
return ans | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My solution using a Queue