每日5题(2)
//根据二叉树的前序序列和中序序列恢复二叉树,输出二叉树的层次遍历序列
//重构二叉树PreOrder & inOrder //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: unorder_map<int, int>pos;//position TreeNode * buildTree(vector<int> & preOrder, vector<int> & inOrder){ int n = inOrder.size(); for (int i = 0; i < n; i++){ pos[inOrder[i]] = i; } dfs(preOrder, inOrder, 0, n - 1, 0, n - 1); } TreeNode * dfs(vector<int>&pre, vector<int>&in, int pl, int pr, int il, int ir){ if (pl>pr){ return NULL;//递归边界 } //找到对应的前序序列和中序序列 int k = pos[pre[pl]]-il;//根节点在中序序列中的位置 TreeNode * root = new TreeNode(pre[pl]); root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1); root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir); return root; } };
(2) Fabonacci数列的求法
dp 递归 矩阵(机试指南) 滚动数组
//滚动数组
int Fabonacci(int n){
int a=0,b=1;
while(n--){
c=a+b;
a=b;
b=c;
}
return a;
}
(3)求二叉树中序遍历节点的后继
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* p) {
if(p->right){
p=p->right;
while(p->left){
p=p->left;
}
return p;
}else{
while(p->father&&p==p->father->right){
p=p->father;
}
return p->father;
}
}
};
(4)求字符矩阵的路径dfs,恢复现场
class Solution {
public:
bool hasPath(vector<vector<char>>& matrix, string &str) {
for(int i=0;i<matrix.size();i++){
for(int j=0;j<matrix[i].size();j++){
if(dfs(matrix,str,0,i,j)){
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& matrix,string &str,int u,int x,int y){
if(str[u]!=matrix[x][y]){return false;}
if(u==(str.size()-1)){
return true;
}
int fx[4]={-1,0,1,0};
int fy[4]={0,1,0,-1};
char t=matrix[x][y];
matrix[x][y]='*';
int a, b;
for(int i=0;i<4;i++){
a=x+fx[i];
b=y+fy[i];
if(a>=0&&a<matrix.size()&&b>=0&&b<matrix[a].size()){
if(dfs(matrix,str,u+1,a,b)){
return true;
}
}
}
matrix[x][y]=t;
return false;
}
};
(5)二叉树中找从根节点出发的和为给定值的路径 dfs+回溯
//二叉树中找从根节点出发的和为给定值的路径 dfs+回溯
class Solution{
public:
vector<vector<int>> res;
vector<int> cur;
vector<vector<int>> findPath(TreeNode * root, int sum){
dfs(root, sum);
return res;
}
void dfs(TreeNode * root, int sum){
if (!root){ return; }
sum -= root->val;
cur.push_back(root->val);
if (!root->left&&!root->right&&!sum){
res.push_back(cur);
}
if (root->left){
dfs(root->left, sum);
}
if (root->right){
dfs(root->right, sum);
}
cur.pop_back();
}
};

浙公网安备 33010602011771号