Swift solution - InOrder traversal


  • 0
    class Solution {
        func getMinimumDifference(_ root: TreeNode?) -> Int {
            var prev: TreeNode? = nil
            var minDiff = Int.max
            
            inorder(root, &prev, &minDiff)
            
            return minDiff
        }
        
        private func inorder(_ root: TreeNode?, _ prev: inout TreeNode?, _ minDiff: inout Int) {
            guard let root = root else {
                return
            }
            
            inorder(root.left, &prev, &minDiff)
            if prev != nil {
                minDiff = min(minDiff, root.val - prev!.val)
            }
            prev = root
            inorder(root.right, &prev, &minDiff)
        }
    }
    

Log in to reply
 

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