6. 重建二叉树
递归构建二叉树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode* root=reConstructBinaryTree(pre,0,pre.size()-1,vin,0,vin.size()-1);
return root;
}
private:
TreeNode* reConstructBinaryTree(vector<int> pre,int pbegin,int pend,vector<int> vin,int vbegin,int vend) {
if(pbegin>pend || vbegin>vend) return NULL;
TreeNode* root = new TreeNode(pre[pbegin]);
for(int i=vbegin;i<=vend;i++){
//根据前序找根节点
//找到中序中根节点的位置
//分左右重新计算
if(vin[i]==pre[pbegin]){
//pbegin+(i-vbegin):(i-vbegin)是中序左分支节点个数
root->left=reConstructBinaryTree(pre,pbegin+1,pbegin+i-vbegin,vin,vbegin,i-1);
root->right=reConstructBinaryTree(pre,pbegin+i-vbegin+1,pend,vin,i+1,vend);
break;
}
}
return root;
}
};
7. 二叉树的下一个节点
/*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
//有右子节点就输出右侧最左的叶子节点
//本身是父节点的左节点就输出父节点
//本身是父节点的右节点就输出父节点的父节点
if(pNode==NULL) return NULL;
if(pNode->right==NULL){
TreeLinkNode* node=pNode;
while(pNode->next!=NULL){
node=pNode->next;
if(node->left==pNode) return node;
else{
pNode=pNode->next;
}
}
return NULL;
}
else{
TreeLinkNode* rode=pNode->right;
while(rode->left!=NULL){
rode=rode->left;
}
return rode;
}
return NULL;
}
};
8. 用两个栈实现队列
class Solution
{
public:
void push(int node) {
stack1.push(node);
return;
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int i=stack2.top();
stack2.pop();
return i;
}
private:
stack<int> stack1;
stack<int> stack2;
};
9. 斐波那契数列
class Solution {
public:
int Fibonacci(int n) {
if(n<0) return 0;
if(n<=1) return n;
vector<int> nums(n+1,0);
nums[1]=1;
int i=2;
while(i<=n){
nums[i]=nums[i-1]+nums[i-2];
i++;
}
return nums[n];
}
};
class Solution {
public:
int Fibonacci(int n) {
if(n<0) return 0;
if(n<=1) return n;
int x=0,y=1;
n=n-1;
while(n--){
y+=x;
x=y-x;
}
return y;
}
};
10. 跳台阶
//实质上是斐波那契数列的问题,换了个问法
class Solution {
public:
int jumpFloor(int number) {
if(number<=0) return 0;
if(number==1) return 1;
int x=0,y=1;
while(number--){
y+=x;
x=y-x;
}
return y;
}
};