二叉樹,中序遍歷+後序遍歷輸出前序遍歷
阿新 • • 發佈:2018-12-15
引用:
https://blog.csdn.net/m0_37698652/article/details/79218014
#include <iostream> #include <string> using namespace std; struct TreeNode { struct TreeNode* left; struct TreeNode* right; char elem; }; TreeNode* BinaryTreeFromOrderings(const char*inorder, const char*aftorder, int length) { if (length == 0) { return NULL; } TreeNode* node = new TreeNode; node->elem = *(aftorder + length - 1);//後序遍歷的最後一個結點為根結點 cout << node->elem;//輸出當前結點 int rootIndex = 0; for (; rootIndex < length; rootIndex++)//確定根結點位置 { if (inorder[rootIndex] == *(aftorder + length - 1))//中序遍歷中,根結點左側為左子樹,右側為右子樹 break; } //遞迴 node->left = BinaryTreeFromOrderings(inorder, aftorder, rootIndex); node->right = BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex, length - (rootIndex + 1)); return node; } int main() { int n; cout << "請輸入二叉樹結點數量" << endl; while (cin >> n) { string ins, afs; cout << "請輸入中序遍歷結果(字元間無間隔)" << endl; cin >> ins; cout << "請輸入後序遍歷結果(字元間無間隔)" << endl; cin >> afs; const char*in = ins.data(); const char*af = afs.data(); cout << "該二叉樹的前序遍歷結果為" << endl; BinaryTreeFromOrderings(in, af, n); cout << endl << endl; cout << "請輸入二叉樹結點數量" << endl; } return 0; }