上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode* root) {
}
};
golang 解法, 执行用时: 12 ms, 内存消耗: 6.2 MB, 提交时间: 2021-06-18 15:43:59
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findMode(root *TreeNode) (answer []int) {
var base, count, maxCount int
update := func(x int) {
if x == base {
count++
} else {
base, count = x, 1
}
if count == maxCount {
answer = append(answer, base)
} else if count > maxCount {
maxCount = count
answer = []int{base}
}
}
var dfs func(*TreeNode)
dfs = func(node *TreeNode) {
if node == nil {
return
}
dfs(node.Left)
update(node.Val)
dfs(node.Right)
}
dfs(root)
return
}