题意:寻找二叉查找树中出现次数最多的值
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ma = 0; int cnt = 1; TreeNode *pre = NULL; vector<int> ans; void inorder(TreeNode* root){ if(root == NULL) return; inorder(root -> left); if(pre){ if(pre -> val == root -> val){ ++cnt; } else{ if(cnt > ma){ ma = cnt; ans.clear(); ans.push_back(pre -> val); } else if(cnt == ma){ ans.push_back(pre -> val); } cnt = 1; } } pre = root; inorder(root -> right); } vector<int> findMode(TreeNode* root) { if(root == NULL) return ans; inorder(root); if(cnt > ma){ ans.clear(); ans.push_back(pre -> val); } else if(cnt == ma){ ans.push_back(pre -> val); } return ans; } };
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12609761.html
时间: 2024-11-05 19:36:24