Created
June 11, 2015 10:06
-
-
Save codetalks-new/40f5166e8bb881eeb9e0 to your computer and use it in GitHub Desktop.
https://leetcode.com/problems/binary-tree-inorder-traversal/ Swift solution
This file contains hidden or 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
// https://leetcode.com/problems/binary-tree-inorder-traversal/ | |
class TreeNode{ | |
let val:Int | |
var left:TreeNode? | |
var right:TreeNode? | |
init(val:Int){ | |
self.val = val | |
} | |
} | |
func inorderTraversal(rootTreeNode:TreeNode) -> [Int]{ | |
var nodeList = [TreeNode]() | |
var arr = [Int]() | |
var current:TreeNode = rootTreeNode | |
nodeList.append(rootTreeNode) | |
while(!nodeList.isEmpty ){ | |
// 一直向左走 move to left | |
while(current.left != nil){ | |
nodeList.append(current.left!) | |
current = current.left! | |
} | |
// no way ,backforward | |
let left = nodeList.removeLast() | |
arr.append(left.val) | |
// turn right a step | |
if let right = left.right{ | |
current = right | |
nodeList.append(right) | |
} | |
} | |
return arr | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment