Skip to content

Commit

Permalink
[Tree] add solutions to Binary Tree Level Order Traversal and Binary …
Browse files Browse the repository at this point in the history
…Tree Level Order Traversal II
  • Loading branch information
Yi Gu committed Apr 5, 2016
1 parent 5489a4e commit f7f7188
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Tree/BinaryTreeLevelOrderTraversal.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Question Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
* Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
* Time Complexity: O(n), Space Complexity: O(n)
*
* 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 BinaryTreeLevelOrderTraversal {
func levelOrder(root: TreeNode?) -> [[Int]] {
var res: [[Int]] = []
var queue:[TreeNode] = []

if root == nil {
return res
}

queue.append(root!)

while queue.count > 0 {
var size: Int = queue.count
var level: [Int] = []

for i in 1...size {
let node: TreeNode = queue[0]
queue.removeAtIndex(0)

level.append(node.val)
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
res.append(level)
}

return res
}
}
54 changes: 54 additions & 0 deletions Tree/BinaryTreeLevelOrderTraversalII.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Question Link: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
* Primary idea: use a queue to help hold TreeNode, and for each level add a new Int array
*
* Note: use method insertAtIndex to add each level to final result
*
* Time Complexity: O(n), Space Complexity: O(n)
*
* 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 BinaryTreeLevelOrderTraversalII {
func levelOrderBottom(root: TreeNode?) -> [[Int]] {
var res: [[Int]] = []
var queue: [TreeNode] = []

if root == nil {
return res
}

queue.append(root!)

while queue.count > 0 {
var size: Int = queue.count
var level: [Int] = []

for i in 1...size {
let node: TreeNode = queue[0]
queue.removeAtIndex(0)

level.append(node.val)
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
res.insert(level, atIndex:0)
}

return res
}
}

0 comments on commit f7f7188

Please sign in to comment.