Skip to content

Commit

Permalink
[Stack] add Solution to Preorder Traversal and Simplify Path
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed May 20, 2016
1 parent 6557bf1 commit e7048c2
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
37 changes: 37 additions & 0 deletions Stack/PreorderTraversal.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Question Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
* Primary idea: Use a stack to help iterate the tree
* 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 PreorderTraversal {
func preorderTraversal(root: TreeNode?) -> [Int] {
var res = [Int]()
var stack = [TreeNode]()
var node = root

while !stack.isEmpty || node != nil {
if node != nil {
res.append(node!.val)
stack.append(node!)
node = node!.left
} else {
node = stack.removeLast().right
}
}

return res
}
}
36 changes: 36 additions & 0 deletions Stack/SimplifyPath.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Question Link: https://leetcode.com/problems/simplify-path/
* Primary idea: Use a stack, normal to push, .. to pop
* Time Complexity: O(n), Space Complexity: O(n)
*/

class SimplifyPath {
func simplifyPath(path: String) -> String {
var res = ""
var stack = [String]()
let paths = path.characters.split {$0 == "/"}.map(String.init)

for path in paths {
var path = path.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

guard path != "." else {
continue
}

if path == ".." {
if (stack.count > 0) {
stack.removeLast()
}
} else if path.characters.count > 0 {
stack.append(path)
}
}

for str in stack {
res += "/"
res += str
}

return res.isEmpty ? "/" : res
}
}

0 comments on commit e7048c2

Please sign in to comment.