Swift solution


  • 0
    S
    /**
     * 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 {
        private var prev: TreeNode? = nil
        private var modes = [Int]()
        private var countMode = 0
        private var countTemp = 0
        
        func findMode(_ root: TreeNode?) -> [Int] {
            guard let node = root else { return modes }
            findMode(node.left)
            visitNode(node)
            findMode(node.right)
            return modes 
        }
        
        private func visitNode(_ root: TreeNode) {
            defer { prev = root }
    
            guard let prev = prev else {
                if modes.isEmpty {
                    modes = [root.val]
                    countTemp = 1
                    countMode = countTemp
                }
                return
            }
    
            countTemp = prev.val == root.val ? countTemp + 1 : 1
    
            if countTemp == countMode {
                modes += [root.val]
            } else if countMode < countTemp {
                countMode = countTemp
                modes = [root.val]
            }
        }
    }
    

Log in to reply
 

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