面试题07. 重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。且假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
思路:递归传递中的序列下标
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
//二叉树的前序遍历中的第一位一定是根节点
if(preorder.size()==0||inorder.size()==0)return NULL;
//找到根节点在中序遍历中的位置,中序遍历之前的节点都是左子树节点,之后都是右子树节点
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder,int a1,int b1,vector<int>& inorder,int a2,int b2){
TreeNode* root=new TreeNode(preorder[a1]);//创建当前的根节点
int i=a2;
while(inorder[i]!=preorder[a1])i++;//找到当前根节点在中序遍历中的位置i
int left=i-a2; //左子树的长度
int right=b2-i; //右子树的长度
if(left>0)root->left=build(preorder,a1+1,a1+left,inorder,a2,i-1); //递归求解左子树
if(right>0)root->right=build(preorder,a1+left+1,b1,inorder,i+1,b2);//递归求解右子树
return root;
}
};
懵ing。。。。。
面试题09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路:栈a进入,栈b出队列;进行入队时,压入栈a
出队是,先检查栈a,b是否为空;a,b均为空,返回-1;b非空,返回b栈顶;a非空,b空,将栈a中元素全部压入栈b
class CQueue {
public:
stack<int> a;
stack<int> b;
CQueue() {
}
void appendTail(int value) {
a.push(value);
}
int deleteHead() {
if (b.empty() && a.empty())
return -1;
else if (b.empty() && !a.empty())
{
while (!a.empty())
{
b.push(a.top());
a.pop();
}
}
int temp = b.top();
b.pop();
return temp;
}
};
懵Doub… ing…