Swift solution - iterative, recursive


  • 0
    class Solution {
        func inorderTraversal(_ root: TreeNode?) -> [Int] {
            var result = [Int]()
            var stack = [TreeNode]()
            var current = root
            
            while current != nil || !stack.isEmpty {
                if current != nil {
                    stack.append(current!)
                    current = current?.left
                } else {
                    current = stack.removeLast()
                    result.append(current!.val)
                    current = current?.right
                }
            }
            
            return result
        }
        
        func inorderTraversal_Rec(_ root: TreeNode?) -> [Int] {
            var result = [Int]()
            
            helper(root, &result)
            
            return result
        }
        
        fileprivate func helper(_ root: TreeNode?, _ result: inout [Int]) {
            guard let root = root else {
                return
            }
            
            helper(root.left, &result)
            result.append(root.val)
            helper(root.right, &result)
        }
    }
    

Log in to reply
 

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