轉載請註明作者和出處: http://blog.csdn.net/c406495762
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).
題目:找到二叉搜索樹中的所有mode(出現最頻繁的元素)。
思路:這裏定義的二叉搜索樹的一個結點的左子樹中所有結點的值都小於或等於該結點的值,右子樹則相反,大於或等於。於此同時,follow up說讓我們不用除了遞歸中的隱含棧之外的額外空間,因此不能使用哈希表。由於是二叉搜索樹,那麼我們中序遍歷出來的結果就是有序的,我們只需要比較前後兩個元素是否相等,就能統計某個元素出現的次數,因爲相同的元素可定是都在一起的。我們需要一個結點變量pre來記錄上一個遍歷到的結點,然後mx記錄最大的次數,cnt計數當前元素出現的次數。中序遍歷的時候,如果pre不爲空,說明當前不是第一個結點,我們和之前一個結點比較,如果相等,則cnt自增1,如果不等,cnt重置1。如果此時cnt大於mx,那麼我們清空結果res,並把當前結點值放入結果res,如果cnt等於mx,那麼我們直接將當前結點值加入結果res,然後mx賦值爲cnt。最後我們把pre更新爲當前結點。如果pre爲空,說明當前結點是根結點。那麼我們新建一個結點並賦上當前結點值。
Language : cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if (!root) return {};
vector<int> res;
TreeNode *now = root, *pre = NULL;
stack<TreeNode*> s;
int mx = 0, cnt = 1;
while (!s.empty() || now) {
while (now) { //中序遍歷,左中右。將每個結點的左子樹入棧
s.push(now);
now = now->left;
}
now = s.top(); s.pop(); //取棧頂元素
if (pre) { //判斷當前元素和上一個元素值是否一樣,一樣cnt計數加一
cnt = (now->val == pre->val) ? cnt + 1 : 1;
} //如果cnt大於等於mx,說明當前元素重複次數大於之前最大的重複元素的次數,需要將新結果入結果棧。
if (cnt >= mx) {
if (cnt > mx) res.clear();
res.push_back(now->val);
mx = cnt;
}
if (!pre) pre = new TreeNode(now->val);
pre->val = now->val;
now = now->right;
}
return res;
}
};
Language : python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
s = []
now = root
pre = None
mx, cnt = 0, 1
while s or now:
while now:
s.append(now)
now = now.left
now = s.pop(len(s) - 1)
if pre:
if now.val == pre.val:
cnt = cnt + 1
else:
cnt = 1
if cnt >= mx:
if cnt > mx:
del res[:]
res.append(now.val)
mx = cnt
if not pre:
pre = TreeNode(now.val)
pre.val = now.val
now = now.right
return res