一种简单的写法是中序遍历输出成数组,然后在数组内判断递增;另一种就是下面这种写法;
- class Solution {
- public:
-
- int result = 100000;
- TreeNode* previous = NULL;
-
- void traversal(TreeNode* cur) { //左中右遍历的时候这个搜索二叉树就是一个递增数列
- if (cur == NULL) return;
- traversal(cur->left);
- if (previous != NULL) { //这句话是防止下面那句话操作空指针的val,同时也确保了在叶子结点便利的时候不会进行减法操作
- result = min(result, cur->val - previous->val);
- }
- previous = cur; //注意这句话要放在if之外
- traversal(cur->right);
- }
-
- int getMinimumDifference(TreeNode* root) {
- traversal(root);
- return result;
- }
- };
- */
- class Solution {
- public:
- int count;
- int maxcount;
- TreeNode *pre = NULL;
- vector<int> result;
-
- void searchBST(TreeNode* root){
- if (root == NULL) return;
- searchBST(root->left);
- if (pre == NULL) {
- count = 1;
- } else if (pre->val == root->val) {
- count ++;
- }else {
- count = 1;
- }
- pre = root;
- if (count == maxcount) {
- result.push_back(root->val);
- }
- if(count > maxcount) {
- maxcount = count;
- result.clear();
- result.push_back(root->val);
- }
- searchBST(root->right);
- }
-
- vector<int> findMode(TreeNode* root) {
- count =0;
- maxcount=0;
- searchBST(root);
- return result;
- }
- };