Swift solution - iterative, recursive


  • 0
    class Solution {
        func postorderTraversal(_ root: TreeNode?) -> [Int] {
            guard let root = root else {
                return []
            }
            
            var result = [Int]()
            var stack = [root]
            
            while !stack.isEmpty {
                let node = stack.removeLast()
                result.append(node.val)
                if let leftNode = node.left {
                    stack.append(leftNode)
                }
                if let rightNode = node.right {
                    stack.append(rightNode)
                }
            }
            
            return result.reversed()
        }
        
        func postorderTraversal_Rec(_ root: TreeNode?) -> [Int] {
            var result = [Int]()
            
            postorder(root, &result)
            
            return result
        }
        
        private func postorder(_ root: TreeNode?, _ result: inout [Int]) {
            guard let root = root else {
                return
            }
            
            postorder(root.left, &result)
            postorder(root.right, &result)
            result.append(root.val)
        }
    }
    

Log in to reply
 

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