mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
JavaScript版本的《二叉搜索树中的众数》
This commit is contained in:
@ -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;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user