题目1(二叉树与双向链表)
收获
1:学会了用递归遍历的方法遍历二叉树并和链表相结合~
代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode *head=NULL;
TreeNode *pre=NULL;
TreeNode* Convert(TreeNode* pRootOfTree) {
if(pRootOfTree==NULL)
return NULL;
Convert(pRootOfTree->left);
if(pre==NULL)
{
head=pRootOfTree;
pre=pRootOfTree;
}
else{
pre->right=pRootOfTree;
pRootOfTree->left=pre;
pre=pRootOfTree;
}
Convert(pRootOfTree->right);
return head;
}
};
题目2(重建二叉树)
收获
1:学会了根据先序遍历和中序遍历创建二叉树~(或许可以自己尝试一下已知中序和后序遍历的结果创建应该是什么样子的)
2:能够自己默写下来并进行后期的应用~
代码
/**
* 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) {
int n=pre.size();
int m=vin.size();
if(n==0||m==0)
return NULL;
TreeNode *root=new TreeNode(pre[0]);
for(int i=0;i<n;i++){
if(vin[i]==pre[0]){
vector<int>leftpre(pre.begin()+1,pre.begin()+i+1);
vector<int>leftvin(vin.begin(),vin.begin()+i);
root->left=reConstructBinaryTree(leftpre, leftvin);
vector<int>rightpre(pre.begin()+i+1,pre.end());
vector<int>rightvin(vin.begin()+i+1,vin.end());
root->right=reConstructBinaryTree(rightpre, rightvin);
break;
}
}
return root;
}
};
题目3(输出二叉树的右视图)
收获
1:将前面学到的建树方法进行应用~
2:练习了用层次遍历的方法统计最右面的右视图~
代码
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型vector 先序遍历
* @param zhongxu int整型vector 中序遍历
* @return int整型vector
*/
// 根据先序遍历和中序遍历建树建树
TreeNode *CreateTree(vector<int>&xianxu,vector<int>&zhongxu){
int n=xianxu.size();
int m=zhongxu.size();
if(n==0)
return NULL;
TreeNode *root=new TreeNode(xianxu[0]);
for(int i=0;i<n;i++){
if(zhongxu[i]==xianxu[0]){
vector<int>xianxuleft(xianxu.begin()+1,xianxu.begin()+i+1);
vector<int>zhongxuleft(zhongxu.begin(),zhongxu.begin()+i);
root->left=CreateTree(xianxuleft,zhongxuleft);
vector<int>xianxuright(xianxu.begin()+i+1,xianxu.end());
vector<int>zhongxuright(zhongxu.begin()+i+1,zhongxu.end());
root->right=CreateTree(xianxuright,zhongxuright);
break;
}
}
return root;
}
// 层次遍历找到每层最右面的节点
vector<int> viewright(TreeNode*root){
vector<int>res;
if(root==NULL)
return res;
TreeNode *cur=root;
queue<TreeNode *>q;
q.push(cur);
while(!q.empty()){
int n=q.size();
for(int i=0;i<n;i++){
cur=q.front();
q.pop();
if(cur->left){
q.push(cur->left);
}
if(cur->right){
q.push(cur->right);
}
}
res.push_back(cur->val);
}
return res;
}
vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) {
// write code here
vector<int>res;
if(xianxu.size()==0)
return res;
TreeNode *root=CreateTree(xianxu, zhongxu);
res=viewright(root);
return res;
}
};