JavaScript版本的《二叉搜索树中的众数》

This commit is contained in:
kok-s0s
2021-06-21 21:33:43 +08:00
parent 8969d0fd65
commit 4f66b8679c

View File

@ -523,6 +523,55 @@ func traversal(root *TreeNode,result *[]int,pre *TreeNode){//遍历统计
} }
``` ```
JavaScript版本
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findMode = function (root) {
let maxCount = 0;
let curCount = 0;
let pre = null;
let res = [];
const inOrder = (root) => {
if (root === null)
return;
inOrder(root.left);
if (pre === null)
curCount = 1;
else if (pre.val === root.val)
curCount++;
else
curCount = 1;
pre = root;
if (curCount === maxCount)
res.push(root.val);
if (curCount > maxCount) {
maxCount = curCount;
res.splice(0, res.length);
res.push(root.val);
}
inOrder(root.right);
return;
}
inOrder(root);
return res;
};
```
----------------------- -----------------------