O(n) declarative JS solution using


  • 0
    L
    function findMode(root){
    	var results = {}
    	if (root === null) return []
    	var cardinality = 0
    	inOrder(root,function (node){
    		results[node.val] = ++results[node.val] || 1
    		if (results[node.val] > cardinality) {
    			cardinality = results[node.val]
    		}
    	})
    	return Object
    		.keys(results)
    		.filter(k => results[k] === cardinality)
    		.map(str => parseInt(str))
    }
    
    function inOrder(node,cb){
    	if (node.left !== null) { inOrder(node.left,cb)}
    	cb(node)
    	if (node.right !== null){ inOrder(node.right,cb);}
    }
    

Log in to reply
 

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