501. Find Mode in Binary Search Tree

时间:2020-09-24 22:11:03   收藏:0   阅读:80

https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/

class Solution {
public:
	int count = 0, max_count = 0;
	TreeNode* pre = NULL;
	vector<int> ans;
	void dfs(TreeNode* node) {
		if (node == NULL) return;
		dfs(node->left);
		if (pre == NULL) {
			count++;
			ans.push_back(node->val);
		}
		else if (pre->val == node->val) {
			++count;
		}
		else if (pre->val != node->val) {
			count = 1;
		}
		
		
		if (count == max_count) {
			ans.push_back(node->val);
		}
		else if (count >= max_count) {
			max_count = count;
			ans.clear();
			ans.push_back(node->val);
		}
		pre = node;
		dfs(node->right);
		return;
	}



	vector<int> findMode(TreeNode* root) {
		if (root == NULL) {
			return {};
		}
		dfs(root);
		return ans;
	}
};
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!