Swift solution - InOrder traversal without global variable


  • 0
    class Solution {
        func findMode(_ root: TreeNode?) -> [Int] {
            guard let root = root else {
                return []
            }
            
            var result = [Int]()
            var prev: Int? = nil
            var count = 1
            var maxCount = 0
            
            helper(root, &prev, &count, &maxCount, &result)
            
            return result
        }
        
        func helper(_ root: TreeNode?, _ prev: inout Int?, _ count: inout Int, _ maxCount: inout Int, _ result: inout [Int]) {
            guard let root = root else {
                return
            }
            
            helper(root.left, &prev, &count, &maxCount, &result)
            handleValue(root.val, &prev, &count, &maxCount, &result)
            helper(root.right, &prev, &count, &maxCount, &result)
        }
        
        func handleValue(_ value: Int, _ prev: inout Int?, _ count: inout Int, _ maxCount: inout Int, _ result: inout [Int]) {
            if let prev = prev {
                if value == prev {
                    count += 1
                } else {
                    count = 1
                }
            }
            if count > maxCount {
                maxCount = count
                result.removeAll()
                result.append(value)
            } else if (count == maxCount) {
                result.append(value)
            }
            prev = value
        }
    }
    

Log in to reply
 

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