Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangqiaoboy/a7d24ac5ca266d650aaa91615f39ffae to your computer and use it in GitHub Desktop.
Save tangqiaoboy/a7d24ac5ca266d650aaa91615f39ffae to your computer and use it in GitHub Desktop.
iOS 面试题(12):按层遍历二叉树的节点
//
// 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
}
}
@JakeLin
Copy link

JakeLin commented Feb 6, 2017

My solution using a Queue

/**
 * Definition for a binary tree node.
 * public 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
 *     }
 * }
 */
class Solution {
    func levelOrder(_ root: TreeNode?) -> [[Int]] {
      guard let root = root else { return [] }
      
      var levelLast = root
      var last = root
      var queue: [TreeNode] = [root]
      
      var result: [[Int]] = [[Int]]()
      var levelResult: [Int] = [Int]()
      while !queue.isEmpty {
        let node = queue.removeFirst()
        levelResult.append(node.val)
        
        if let left = node.left {
          last = left
          queue.append(left)
        }
        
        if let right = node.right {
          last = right
          queue.append(right)
        }
        
        // the current level is done
        if node === levelLast {
          result.append(levelResult)
          levelResult = [Int]()
          levelLast = last
        }
      }
      
      return result
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment