根据二叉树先序和中序,输出二叉树后序遍历

二叉树后序遍历

http://www.nowcoder.com/questionTerminal/c8dbc39e4c784cc69c8f263b32220165

include

include

include

using namespace std;
class TreeNode {
public:
char val;
TreeNode* left;
TreeNode* right;
TreeNode(int value) :val(value) { this->left = this->right = NULL; };
};
TreeNode* Construct(vector<char>pre, vector<char>vin) {
if (pre.size() == 0 || vin.size() == 0) { return NULL; }
TreeNode* root = new TreeNode(pre[0]);
root->left = root->right = NULL;
vector<char>leftpre, rightpre, leftvin, rightvin;
int i = 0;
for (; i<vin.size(); ++i) {
if (vin[i] == pre[0]) { break; }
leftvin.push_back(vin[i]);
}
if (i<=vin.size()) {
for (int j = i + 1; j<vin.size(); ++j) {
rightvin.push_back(vin[j]);
}
for (int j = 1; j <= i; ++j) {
leftpre.push_back(pre[j]);
}
for (int j = i + 1; j<vin.size(); ++j) {
rightpre.push_back(pre[j]);
}
root->left = Construct(leftpre, leftvin);
root->right = Construct(rightpre, rightvin);
return root;
}
else {
return NULL;
}
}
void lastsearch(TreeNode* temp, vector<char>&vec) {
if (temp->left != NULL) { lastsearch(temp->left, vec); }
if (temp->right != NULL) { lastsearch(temp->right, vec); }
vec.push_back(temp->val);
}
int main() {
vector<char>m_a, m_b, m_c;
string a, b;
cin >> a >> b;
for (int i = 0; i < a.size(); ++i) {
m_a.push_back(a[i]);
m_b.push_back(b[i]);
}
TreeNode* root = Construct(m_a, m_b);
lastsearch(root, m_c);
for (int i = 0; i<m_c.size(); ++i) { cout << m_c[i]; }cout << endl;
cin.get();
cin.get();
return 0;
}</char></char></char></char></char>

全部评论

相关推荐

Noob1024:一笔传三代,人走笔还在
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务