My Swift solution - In-Order Traversal


  • 0
    class Solution {
        var firstElement: TreeNode? = nil
        var secondElement: TreeNode? = nil
        var prevElement = TreeNode(Int.min)
        
        func recoverTree(_ root: TreeNode?) {
            inOrderTraverse(root)
            
            let temp = firstElement!.val
            firstElement!.val = secondElement!.val
            secondElement!.val = temp
        }
        
        func inOrderTraverse(_ root: TreeNode?) {
            if root == nil {
                return
            }
            
            inOrderTraverse(root?.left)
            
            if firstElement == nil && prevElement.val >= root!.val {
                firstElement = prevElement
            }
            
            if firstElement != nil && prevElement.val >= root!.val {
                secondElement = root
            }
            prevElement = root!
            
            inOrderTraverse(root?.right)
        }
    }
    

Log in to reply
 

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