501. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than or equal to the node's key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
- Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2]
,
1
\
2
/
2
return [2]
.
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
求一棵二叉搜索树结点相等值的最大个数
利用BST中序遍历后为排序数组的特点,相等的数是连续的
C++(15ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 TreeNode* prev = NULL ; 13 int count = 1; 14 int max = 0 ; 15 public: 16 vector<int> findMode(TreeNode* root) { 17 vector<int> res ; 18 if (root == NULL) 19 return res; 20 traverse(root , res) ; 21 return res ; 22 } 23 void traverse(TreeNode* root , vector<int>& res){ 24 if (root == NULL) 25 return ; 26 traverse(root->left , res) ; 27 if (prev != NULL){ 28 if (root->val == prev->val) 29 count++ ; 30 else 31 count = 1; 32 } 33 if (count > max){ 34 res.clear() ; 35 max = count ; 36 res.push_back(root->val) ; 37 }else if (count == max){ 38 res.push_back(root->val) ; 39 } 40 prev = root ; 41 traverse(root->right , res) ; 42 43 } 44 };