Using stack in swift,without recursion

• class Solution {

func rightSideView(_ root: TreeNode?) -> [Int] {
var arr:Array<Int> = []
var stack:Array<TreeNode> = []
var currentLength = 0
var maxLength = 0
if root != nil {
currentLength += 1
arr.append(root!.val)
stack.append(root!)
while stack.isEmpty == false {
if stack.last!.right != nil {
stack.append(stack.last!.right!)
currentLength += 1
if currentLength > maxLength {
maxLength = currentLength
arr.append(stack.last!.val)
}
}else if stack.last!.left != nil {
stack.append(stack.last!.left!)
currentLength += 1
if currentLength > maxLength {
maxLength = currentLength
arr.append(stack.last!.val)
}
}else {
while stack.isEmpty == false {
var t = stack.removeLast()
currentLength -= 1
if stack.isEmpty == true {
break
}
if stack.last!.right != nil && t === stack.last!.right! {
if stack.last!.left != nil {
stack.append(stack.last!.left!)
currentLength += 1
break
}
}
}
}
}
}
return arr
}

}

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.