【LeetCode & 剑指offer刷题】熟悉OJ平台3:OJ编程实例
【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
OJ编程实例
给定一棵二叉树的前序(根、左、右)和中序(左、根、右)的打印结果,输出此二叉树按层(从左往右)打印结果。
例如一棵二叉树前序:1 2 4 5 3;中序:4 2 5 1 3。可以构建出下图所示二叉树:
按层打印的结果则为:1 2 3 4 5。
按层打印二叉树(去哪儿网2017春招真题)
题目描述
using namespace std;
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) :val(x), left(NULL), right(NULL) {} //参数初始化列表
};
using iter = vector<int>::iterator;
TreeNode* createTree(iter prebegin, iter preend, iter inbegin, iter inend);
void levelOrder(TreeNode* root);
int main()
{
/* if (freopen("./src/input.txt", "r", stdin))//代替手工输入,需加<cstdio>头文件,vs默认路径起点为工程文件所在的目录
cout << "读取成功" << endl;
else
cout << "读取文件失败" << endl;*/
int n;
cin >> n;
vector<int> preorder(n);
vector<int> inorder(n);
for (int i = 0; i<n; i++)
{
cin >> preorder[i];
}
for (int i = 0; i<n; i++)
{
cin >> inorder[i];
}
TreeNode* root = createTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
levelOrder(root);
return 0;
}
TreeNode* createTree(iter prebegin, iter preend, iter inbegin, iter inend)
{
if (prebegin >= preend || inbegin >= inend) return nullptr;
TreeNode* root = new TreeNode(*prebegin);
iter root_pos = find(inbegin, inend, root->val);
int left_length = root_pos - inbegin;
root->left = createTree(prebegin + 1, prebegin + left_length + 1, inbegin, root_pos);
root->right = createTree(prebegin + left_length + 1, preend, root_pos + 1, inend);
return root;
}
void levelOrder(TreeNode* root)
{
if (root == nullptr) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
int size = q.size();
for (int i = 0; i<size; i++)
{
TreeNode* node = q.front();
cout << node->val << ' ';
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
}