jzhangnu / Leetcode-JS-Solutions

:tropical_drink: Leetcode solutions using JavaScript.
52 stars 7 forks source link

508. Most Frequent Subtree Sum #118

Open jzhangnu opened 6 years ago

jzhangnu commented 6 years ago
let maxCount = 0;
let sumToCount = {};    

function findFrequentTreeSum(root){

    postOrder(root);

    let arr = [];
    for( let i in sumToCount ){
        if(sumToCount[i] == maxCount)arr.push(i)
    }

    return arr
}

function postOrder(root){
    if(root == null)return 0;

    let left = postOrder(root.left);
    let right = postOrder(root.right);

    let sum = left + right + root.val;
    let count;

    if(sumToCount[sum]){
        count = sumToCount[sum] + 1;
        sumToCount[sum]++;
    }
    else{
        sumToCount[sum] = 1;
        count = 1;
    }

    maxCount = Math.max(maxCount, count)

    return sum
}