# 二叉树编程

## 题目描述

//解析： 先重构二叉树  然后利用层次遍历的方式打印出二叉树的右子树
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型vector 先序遍历
* @param zhongxu int整型vector 中序遍历
* @return int整型vector
*/
vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) {
// write code here
if(xianxu.empty() || zhongxu.empty())
{
return {};
}

TreeNode* root = Construct(xianxu, zhongxu, 0, xianxu.size()-1, 0, zhongxu.size()-1);
vector<int> res;

queue<TreeNode*> q;
q.push(root);
//层次遍历 常用的算法可以记住
while(!q.empty())
{
int len = q.size();
TreeNode* t = q.front();
res.push_back(t->val);
while(len--)
{
t = q.front();
q.pop();
if(t->right)
{
q.push(t->right);
}
if(t->left)
{
q.push(t->left);
}
}
}

return res;
}

TreeNode* Construct(vector<int> pre, vector<int> vin, int pl, int pr, int vl, int vr)
{
if(pl > pr || vl > vr)
{
return nullptr;
}

//找到跟节点的索引
int size = 0;
for(int i = vl; i <= vr; i++)
{
if(vin[i] == pre[pl])
{
size = i - vl;
break;
}
}

//利用递归重构二叉树
TreeNode* root = new TreeNode(pre[pl]);
root->left = Construct(pre, vin, pl+1, pl+size, vl, vl+size-1);
root->right = Construct(pre, vin, pl+size+1, pr, vl+size+1, vr);

return root;
}
};

06-16 743

03-14 2450
12-01 4918
12-11 64
05-01 361
03-04 449
11-11 811
09-05 1670
12-01 35
11-29 726
04-24 3723
10-04 516
09-13 11万+
07-23 636
01-29 5890
12-05 1797
07-23 4101
09-02 871