题解 | #输出二叉树的右视图#
输出二叉树的右视图
https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 求二叉树的右视图
* @param preOrder int整型vector 先序遍历
* @param inOrder int整型vector 中序遍历
* @return int整型vector
*/
int current_index = 0; // 前序遍历数组的索引
//建树
TreeNode* reConstructBinaryTree(vector<int>& preOrder, vector<int>& vinOrder) {
if (preOrder.empty() || vinOrder.empty())
return nullptr;
TreeNode* head = new TreeNode(preOrder[current_index]);
vector<int> newLeftVin, newRightVin;
int i = 0;
while (vinOrder[i] != preOrder[current_index]) {
newLeftVin.push_back(vinOrder[i]);
++i;
}
++i;
while (i != vinOrder.size()) {
newRightVin.push_back(vinOrder[i]);
++i;
}
vector<int> newPre;
current_index++;
head->left = reConstructBinaryTree(preOrder, newLeftVin);
head->right = reConstructBinaryTree(preOrder, newRightVin);
return head;
}
//设置双队列,q1放父节点,q2放子节点,每次把q2队尾加入最后结果即可。放完以后把q1更新成q2,并清空q2
vector<int> solve(vector<int>& preOrder, vector<int>& inOrder) {
vector<int> res;
TreeNode* head = reConstructBinaryTree(preOrder, inOrder);
if (!head)
return res;
queue<TreeNode*> q1, q2;
q1.push(head);
int n = q1.back()->val;
res.push_back(n);
while (!q1.empty()) {
while (!q1.empty()) {
if (q1.front()->left) {
q2.push(q1.front()->left);
}
if (q1.front()->right) {
q2.push(q1.front()->right);
}
q1.pop();
}
if (!q2.empty()) {
n = q2.back()->val;
res.push_back(n);
}
while (!q2.empty()) {
q1.push(q2.front());
q2.pop();
}
}
return res;
}
};
方法比较传统,总体就两步:建树+找每层最右节点
建树的思路就不赘述了,请看上一题。找最右节点可以设置双队列,q1放父节点,q2放子节点,每次把q2的队尾,也就是每层的最右节点,加入最后结果即可。放完以后把q1更新成q2,并清空q2

vivo公司福利 364人发布

查看4道真题和解析