Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.node
Assume a BST is defined as follows:less
For example:
Given BST [1,null,2,2]
,spa
1 \ 2 / 2
return [2]
.code
Note: If a tree has more than one mode, you can return them in any order.blog
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).ip
思路:ci
對於本題中的二叉搜索樹,節點的排列是有順序的,左節點<=當前節點<=右節點。也就是說,假設這樣一種狀況:存在大於等於3個的連續相同的節點,且當前節點存在左右子樹,那麼相同的三個節點必定是:當前節點、左子樹中最大的節點和右子樹中最小的節點。element
這裏咱們容易想到的是中序遍歷(對於整個樹,先遍歷左節點,再遍歷中間節點,最後遍歷右節點),使用中序遍歷遍歷二叉搜索樹,能夠得到一個從小到大的排好序的升序序列。get
因此分析到這裏,題目就轉化成:給定一個升序序列,尋找重複次數最多的數字 , 因此
it
/** * 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) { tmp_cnt = 0; max_cnt = 0; cur_value = 0; inorder(root); return result; } private: int tmp_cnt; int max_cnt; int cur_value; vector<int> result; void inorder(TreeNode* root){ if (root == NULL){ return; } // 遍歷左子樹 inorder(root->left); tmp_cnt++; if (cur_value != root-> val){ cur_value = root-> val; tmp_cnt = 1; } if (tmp_cnt > max_cnt){ max_cnt = tmp_cnt; result.clear(); result.push_back(root->val); }else if (tmp_cnt == max_cnt){ result.push_back(root->val); } // 遍歷右子樹 inorder(root->right); } };