Swift solution - PostOrder traversal


  • 0
    class Solution {
        func findFrequentTreeSum(_ root: TreeNode?) -> [Int] {
            var result = [Int]()
            var maxCount = 0
            var sumDict = [Int: Int]()
            var root = root
            
            postOrder(&root, &maxCount, &sumDict)
            
            for (key, value) in sumDict {
                if value == maxCount {
                    result.append(key)
                }
            }
            
            return result
        }
        
        func postOrder(_ root: inout TreeNode?, _ maxCount: inout Int, _ sumDict: inout [Int: Int]) -> Int {
            guard let root = root else {
                return 0
            }
            
            let left = postOrder(&root.left, &maxCount, &sumDict)
            let right = postOrder(&root.right, &maxCount, &sumDict)
            let sum = left + right + root.val
            let count = (sumDict[sum] ?? 0) + 1
            
            sumDict[sum] = count
            maxCount = max(maxCount, count)
            
            return sum
        }
    }
    

Log in to reply
 

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