leetcode501——Find Mode in Binary Search Tree

题目大意:给出的二叉搜索树是含有重复结点的,找出树中出现最频繁的数字,如果有多个出现次数都为最大值的顺序无所谓

分析:dfs。由于二叉搜索树的特点,中序遍历就会得到非降序序列,相同节点是连续的,所以只需要中序遍历二叉搜索树并不断记录每个数字的出现次数,更新最大频率数字即可。

代码:转载自https://blog.csdn.net/liuchuo/article/details/54854037

class Solution {
public:
	vector<int> findMode(TreeNode* root) {
		inorder(root);
		return result;
	}
private:
	vector<int> result;
	int maxCount = 0, currentVal, tempCount = 0;
	void inorder(TreeNode* root) {
		if (root == NULL) return;
		inorder(root->left);
		tempCount++;  //遇到结点,所以它的出现频率加1
		if (root->val != currentVal) {  //遇到的结点和上一节点不同,所以出现频率置1
			currentVal = root->val;  //更新currentVal为当前所遇结点的值
			tempCount = 1;
		}
		if (tempCount > maxCount) {  //出现频率更大,更新答案数组
			maxCount = tempCount;
			result.clear();
			result.push_back(root->val);
		}
		else if (tempCount == maxCount) {  //多个结点的频率都为最大频率
			result.push_back(root->val);
		}
		inorder(root->right);
	}
};

猜你喜欢

转载自blog.csdn.net/tzyshiwolaogongya/article/details/80823444