剑指 Offer 36. 二叉搜索树与双向链表(中序遍历)
class Solution {
public:
Node*pre,*head;
Node* treeToDoublyList(Node* root) {
if(root==NULL) return root;
dfs(root);
head->left=pre;
pre->right=head;
return head;
}
void dfs(Node*root)
{
if(root==NULL)return;
dfs(root->left);
root->left=pre;
if(pre!=NULL)
{
pre->right=root;
}
else head=root;//前面没有结点是头阶段
pre=root;
dfs(root->right);
}
};
剑指 Offer 37. 序列化二叉树
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string data;
queue<TreeNode*>q;
if(!root) return "null";
q.push(root);
TreeNode*t;
while(!q.empty())
{
t=q.front();
q.pop();
if(t)
{
data+=to_string(t->val)+" ";
q.push(t->left);
q.push(t->right);
}
else{
data+="null ";
}
}
if(!data.empty()) data.pop_back();
return data;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data=="null")return NULL;
vector<TreeNode*>bfs;
queue<TreeNode*>q;
stringstream ss(data);
string str_node;
while(ss>>str_node)
{
if(str_node=="null") bfs.push_back(NULL);
else bfs.push_back(new TreeNode(stoi(str_node)));
}
TreeNode*tmp;
q.push(bfs[0]);
int sz=bfs.size();
int idx=1;
while(!q.empty())
{
int s=q.size();
for(int i=0;i<s;i++)
{
tmp=q.front();
q.pop();
if(bfs[idx])
{
tmp->left=bfs[idx];
q.push(bfs[idx]);
}
idx++;
if(bfs[idx])
{
tmp->right=bfs[idx];
q.push(bfs[idx]);
}
idx++;
}
}
return bfs[0];
}
};
剑指 Offer 38. 字符串的排列
class Solution {
public:
vector<string> permutation(string s) {
vector<string>res;
dfs(res,s,0);
return res;
}
void dfs(vector<string>&res,string&s,int pos)
{
if(pos==s.size())
res.push_back(s);
for(int i=pos;i<s.size();i++)
{
bool flag=true;
for(int j=pos;j<i;j++)
{
if(s[i]==s[j])
flag=false;
}
if(flag)
{
swap(s[pos],s[i]);
dfs(res,s,pos+1);
swap(s[pos],s[i]);
}
}
}
};
剑指 Offer 39. 数组中出现次数超过一半的数字
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int>m;
int l=nums.size();
for(int i=0;i<l;i++)
{
m[nums[i]]++;
}
map<int,int>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
if(it->second>l/2)
return it->first;
}
return 0;
}
};
剑指 Offer 40. 最小的k个数
class Solution {
public:
vector<int> getLeastNumbers(vector<int>& arr, int k) {
sort(arr.begin(),arr.end());
vector<int>res;
for(int i=0;i<k;i++)
{
res.push_back(arr[i]);
}
return res;
}
};