forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Stack] add Solution to Preorder Traversal and Simplify Path
- Loading branch information
Yi Gu
committed
May 20, 2016
1 parent
6557bf1
commit e7048c2
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
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
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 | ||
} | ||
} |
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
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 | ||
} | ||
} |