题解 | #输出二叉树的右视图#
输出二叉树的右视图
http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型vector 先序遍历
* @param zhongxu int整型vector 中序遍历
* @return int整型vector
*/
//重构二叉树
TreeNode* reConstruct(vector<int> pre, vector<int> vin)
{
if(pre.size() == 0) return nullptr;
TreeNode* head = new TreeNode(pre[0]);
vector<int> preL, vinL, preR, vinR;
int len = vin.size();
int gen = 0;
for(int i = 0; i < len; ++i)
{
if(vin[i] == pre[0])
{
gen = i;
break;
}
}
for(int i = 0; i < gen; ++i)
{
preL.push_back(pre[i+1]);
vinL.push_back(vin[i]);
}
for(int i = gen+1; i < len; ++i)
{
preR.push_back(pre[i]);
vinR.push_back(vin[i]);
}
head->left = reConstruct(preL, vinL);
head->right = reConstruct(preR, vinR);
return head;
}
//层序遍历,非递归实现,每一层的最后一个节点即是右视图
vector<int> solve(vector<int>& xianxu, vector<int>& zhongxu) {
// write code here
TreeNode* head = reConstruct(xianxu, zhongxu);
vector<int> rst;
if(head == nullptr) return rst;
queue<TreeNode* > que;
que.push(head);
while(!que.empty())
{
int size = que.size();
while(size--)
{
TreeNode* node = que.front();
que.pop();
if(size == 0) rst.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return rst;
}
};