1
#include <iostream>
#include <queue>
using namespace std;
//二叉树定义
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode(int x) : m_nValue(x), m_pLeft(NULL), m_pRight(NULL){}//构造函数
};
typedef BinaryTreeNode* binaryTreeNode;
//根据前序和中序构建二叉树,核心函数
BinaryTreeNode* buildTreeAccordingPreAndIn(int preorder[], int inorder[],
int startPre,
int endPre,
int startIn,
int endIn){
if (startPre > endPre)
return NULL;
int nRootVal = preorder[startPre];
BinaryTreeNode* pRoot = new BinaryTreeNode(nRootVal);
int i, cnt = 0;
for (i = startIn; i <= endIn&&inorder[i] != nRootVal; i++, cnt++);
pRoot->m_pLeft = buildTreeAccordingPreAndIn(preorder, inorder, startPre + 1, startPre + cnt, startIn, i - 1);
pRoot->m_pRight = buildTreeAccordingPreAndIn(preorder, inorder, startPre + cnt + 1, endPre, i + 1, endIn);
return pRoot;
}
//根据前序和中序构建二叉树
BinaryTreeNode* buildTree(int preorder[],int preLength, int inorder[],int inLength) {
return buildTreeAccordingPreAndIn(preorder, inorder, 0, preLength - 1, 0, inLength - 1);
}
//按层遍历
void leverTravel(BinaryTreeNode* pRoot)
{
queue<binaryTreeNode> q;
if(pRoot != NULL)
{
q.push(pRoot);
}
BinaryTreeNode* b;
while(!q.empty())
{
b = q.front();
cout<<b->m_nValue<<" ";
q.pop();
if(b->m_pLeft)
{
q.push(b->m_pLeft);
}
if(b->m_pRight)
{
q.push(b->m_pRight);
}
}
}
int main()
{
int n;
cin>>n;
int preorder[n];
int inorder[n];
for(int i = 0; i < n; i++)
{
cin>>preorder[i];
}
for(int i = 0; i < n; i++)
{
cin>>inorder[i];
}
BinaryTreeNode* pRoot = buildTree(preorder, n, inorder, n);
leverTravel(pRoot);
return 0;
}
牛客上做过原题吧,剑指offer的?构建二叉树,打印二叉树。
2
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
int len = str.length();
long sum = 0;
long x;
for(int i = 0; i < len; i++)
{
x = str[i]-'a';
x *= pow(26, len - i - 1);
sum += x;
}
cout<<sum<<endl;
}
return 0;
}
x如果定义为int 只能过80%。就是范围的问题
3
#include <iostream>
#include <unordered_set>
#include <queue>
using namespace std;
int ladderLength(string start, string end, unordered_set<string> &dict)
{
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//BFS遍历找到的第一个匹配就是最短转换,空字符串是层与层之间的分隔标志
queue<string> Q;
Q.push(start); Q.push("");
int res = 1;
while(Q.empty() == false)
{
string str = Q.front();
Q.pop();
if(str != "")
{
int strLen = str.length();
for(int i = 0; i < strLen; i++)
{
char tmp = str[i];
for(char c = 'a'; c <= 'z'; c++)
{
if(c == tmp)continue;
str[i] = c;
if(str == end)return res+1;
if(dict.find(str) != dict.end())
{
Q.push(str);
dict.erase(str);
}
}
str[i] = tmp;
}
}
else if(Q.empty() == false)
{//到达当前层的结尾,并且不是最后一层的结尾
res++;
Q.push("");
}
}
return 0;
}
int main()
{
string start;
string end;
cin>>start;
cin>>end;
unordered_set<string> dict;
string str;
while(cin>>str)
{
dict.insert(str);
}
int n = ladderLength(start, end, dict);
cout<<n<<endl;
}
Leetcode: Word Ladder原题