Swift Solution


  • 0
    D
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public var val: Int
     *     public var left: TreeNode?
     *     public var right: TreeNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.left = nil
     *         self.right = nil
     *     }
     * }
     */
    class Solution {
        var tilt = 0 
        func findTilt(_ root: TreeNode?) -> Int {
            findTiltSum(root)
            return tilt
        }
        
        func findTiltSum(_ root: TreeNode?) -> Int {
            if root?.val == nil {
                return 0
            }
            var leftSum = findTiltSum(root?.left) 
            
            var rightSum = findTiltSum(root?.right)
            
            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.