501. Find Mode in Binary Search Tree
2018-01-10 15:48
302 查看
1. Description
Given a BST, find the most frequently occurred element in the BST.
2. Solution
Preorder traverse the BST, and store the value of nodes in a vector.
Find the most common element in the vector.
3. Code
Given a BST, find the most frequently occurred element in the BST.
2. Solution
Preorder traverse the BST, and store the value of nodes in a vector.
Find the most common element in the vector.
3. Code
vector<int> findMode(TreeNode* root) { vector<int> ans; if(!root) return ans; stack<TreeNode*>s; while(root){ s.push(root); root = root->left; } int cnt = 0; int a = INT_MAX; int len = 0; while(!s.empty()){ TreeNode* curr = s.top(); s.pop(); if(curr->val == a) cnt++; else{ if(cnt>len){ ans.clear(); ans.push_back(a); len=cnt; } else if(cnt==len){ ans.push_back(a); } cnt=1; a=curr->val; } curr=curr->right; while(curr){ s.push(curr); curr = curr->left; } } if(cnt>len){ ans.clear(); ans.push_back(a); } else if(cnt==len){ ans.push_back(a); } return ans; }
相关文章推荐
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree#2
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- leetcode-501-Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- leetcode 501 Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- Leetcode 501 Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- LeetCode - 501 - Find Mode in Binary Search Tree
- Find Mode in Binary Search Tree:带重复元素的搜索二叉树Morris遍历查找频率最大的元素
- Find Mode in Binary Search Tree
- Find mode in Binary Search Tree