BM41 输出二叉树的右视图
描述
请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图
数据范围:
要求: 空间复杂度 ,时间复杂度
如输入[1,2,4,5,3],[4,2,5,1,3]时,通过前序遍历的结果[1,2,4,5,3]和中序遍历的结果[4,2,5,1,3]可重建出以下二叉树:
所以对应的输出为[1,3,5]。
示例1
输入:
[1,2,4,5,3],[4,2,5,1,3]
复制返回值:
[1,3,5]
复制
备注:
二叉树每个节点的值在区间[1,10000]内,且保证每个节点的值互不相同。
题解
重建二叉树+层次遍历
先通过输入重建二叉树,然后使用层次遍历,在遍历每一层的时候,最后一个节点就是右视图的节点。
代码如下:
// https://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int find_val(std::vector<int> &nums, int left, int right, int val)
{
while (left != right)
{
if (nums[left] == val)
{
return left;
}
left++;
}
return right;
}
TreeNode *build_tree(std::vector<int> &pre, int pre_begin, int pre_end, std::vector<int> &in, int in_begin, int in_end)
{
if (pre_begin == pre_end || in_begin == in_end)
{
return nullptr;
}
auto node = new TreeNode(pre[pre_begin]);
int index = find_val(in, in_begin, in_end, node->val);
int left_count = index - in_begin;
int right_count = in_end - index - 1;
node->left = build_tree(pre, pre_begin + 1, pre_begin + 1 + left_count, in, in_begin, index);
node->right = build_tree(pre, pre_begin + 1 + left_count, pre_end, in, index + 1, in_end);
return node;
}
TreeNode *reConstructBinaryTree(std::vector<int> pre, std::vector<int> vin)
{
return build_tree(pre, 0, pre.size(), vin, 0, vin.size());
}
std::vector<int> solve(std::vector<int> &xianxu, std::vector<int> &zhongxu)
{
std::vector<int> v;
auto root = reConstructBinaryTree(xianxu, zhongxu);
if (root == nullptr)
{
return v;
}
std::queue<TreeNode *> q;
q.push(root);
while (!q.empty())
{
int n = q.size();
while (n-- > 0)
{
auto node = q.front();
q.pop();
if (node->left != nullptr)
{
q.push(node->left);
}
if (node->right != nullptr)
{
q.push(node->right);
}
if (n == 0)
{
v.push_back(node->val);
}
}
}
return v;
}