Title

# 数组转 二叉树 ，并且输出二叉树的右视图

[1,2,4,5,3],[4,2,5,1,3]

[1,3,5]

struct Node {
int val;
Node*left,*right;
Node (int x):val(x),left(NULL),right(NULL) {};

};
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
//中序 确定左右子树，先序确定根节点
deque<Node*> dq;
vector<int>res;
int n = xianxu.size();
Node* root = make_tree(xianxu,zhongxu,0,n-1,0,n-1);
dq.push_back(root);
while(dq.size()) {
int n = dq.size();
while(--n) {
Node* root = dq.front();dq.pop_front();
if (root -> left) dq.push_back(root->left);
if (root -> right) dq.push_back(root-> right);
//一层丢进去
}
Node* r = dq.front();dq.pop_front();
if (r -> left) dq.push_back(r -> left);
if (r -> right) dq.push_back(r -> right);
res.push_back(r -> val);

}

return res;

}

Node * make_tree(vector<int>&pre,vector<int>&mid, int lx,int rx,int lz,int rz) {
if (lx> rx) return NULL;
Node* root = new Node(pre[lx]);

int i=0;
for(i=lz;i<=rz;++i) if(mid[i] == pre[lx]) break;
// 中间节点 划分左右子树
int rightNodeCount = rz - i;
root -> left = make_tree(pre,mid,lx+1,rx-rightNodeCount,lz,i-1);

root -> right = make_tree(pre,mid,rx-rightNodeCount+1,rx,i+1, rz);
return root;
}
};


posted @ 2020-12-01 17:35  .geek  阅读(214)  评论(0编辑  收藏  举报