# \#501 Find Mode in Binary Search Tree ## *給定一sorted binary tree, 回傳出現頻率最高的節點val(陣列型態)* ## Log - build 20210927 by syhuang ## xxx - xxx - leetcode submit runtime xx%, memory xx% ```javascript= ``` ## 初見 - 對tree遍歷並記錄各節點的數字出現次數 - 對記錄做排序 - 取最高的節點val(從第一個開始,直到出現次數變小就停止,即可取得所有同樣最高的節點值) - leetcode submit runtime 22%, memory 5% ```javascript= var findMode = function(root) { let nodes = {}; let sortedNodes = []; let result = []; calcAllNodeValCount(); sortNodesDesc(); let tmp = 0; for(let i=0; i<sortedNodes.length; i++){ if(tmp!=0){ if(tmp==sortedNodes[i][1]) result.push(sortedNodes[i][0]); else break; }else{ tmp = sortedNodes[i][1]; result.push(sortedNodes[i][0]); } } return result; function sortNodesDesc(){ for(let t in nodes){ sortedNodes.push([t,nodes[t]]) } sortedNodes.sort(function(a,b){ return b[1] - a[1]; }) } function calcAllNodeValCount(){ let t = [];//暫存node let p = root; while(p || t.length > 0){ while(p){ addNodeCount(p.val.toString()); t.push(p); p = p.left; } p = t.pop(); p = p.right; } } function addNodeCount(value){ if(typeof nodes[value] != 'undefined') nodes[value] += 1; else nodes[value] = 1; } }; ``` ## 備註 ## 參考 - [較佳解](https://leetcode.com/problems/find-mode-in-binary-search-tree/discuss/98101/Proper-O(1)-space):遍歷tree的同時記錄val出現次數, 以達到space O(1) ###### tags: `leetcode`, `leetcode-easy`, `binary tree`,`tree`