Swift O(n) solution - PostOrder Traversal without global variable


  • 0
    class Solution {
        func findTilt(_ root: TreeNode?) -> Int {
            guard let root = root else {
                return 0
            }
            
            var tilt = 0
            
            findTiltHelper(root, &tilt)
            
            return tilt
        }
        
        func findTiltHelper(_ root: TreeNode?, _ tilt: inout Int) -> Int {
            guard let root = root else {
                return 0
            }
            
            let leftSum = findTiltHelper(root.left, &tilt)
            let rightSum = findTiltHelper(root.right, &tilt)
            
            tilt += abs(leftSum - rightSum)
            
            return leftSum + rightSum + root.val
        }
    }
    

Log in to reply
 

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