首先,咱們看看前序、中序、後序遍歷的特性:
前序遍歷:
1.訪問根節點
2.前序遍歷左子樹
3.前序遍歷右子樹
中序遍歷:
1.中序遍歷左子樹
2.訪問根節點
3.中序遍歷右子樹
後序遍歷:
1.後序遍歷左子樹
2.後序遍歷右子樹
3.訪問根節點node
1、已知前序、中序遍歷,求後序遍歷ios
前序遍歷: GDAFEMHZ算法
中序遍歷: ADEFGHMZ編程
算法流程:oop
1 肯定根,肯定左子樹,肯定右子樹。spa
2 在左子樹中遞歸。code
3 在右子樹中遞歸。blog
4 打印當前根。遞歸
後序遍歷順序爲: AEFDHZMGstring
編程實現:
#include <iostream> #include <fstream> #include <string> struct TreeNode{ struct TreeNode* left; struct TreeNode* right; char elem; }; void BinaryTreeFromOrderings(char* inorder, char* preorder, int length){ if(length == 0){ return; } TreeNode* node = new TreeNode;//Noice that [new] should be written out. node->elem = *preorder; int rootIndex = 0; for(;rootIndex < length; rootIndex++){ if(inorder[rootIndex] == *preorder) break; } //Left BinaryTreeFromOrderings(inorder, preorder +1, rootIndex); //Right BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1)); cout<<node->elem<<endl; return; } int main(int argc, char* argv[]){ printf("Hello World!\n"); char* pr="GDAFEMHZ"; char* in="ADEFGHMZ"; BinaryTreeFromOrderings(in, pr, 8); printf("\n"); return 0; }
2、已知後序、中序遍歷,求前序遍歷
中序遍歷: ADEFGHMZ
後序遍歷: AEFDHZMG
算法流程:
1 肯定根,肯定左子樹,肯定右子樹。
2 打印當前根。
3 在左子樹中遞歸。
4 在右子樹中遞歸。
那麼,前序遍歷: GDAFEMHZ
編程實現:
#include <iostream> #include <fstream> #include <string> struct TreeNode{ struct TreeNode* left; struct TreeNode* right; char elem; }; TreeNode* BinaryTreeFromOrderings(char* inorder, char* aftorder, int length){ if(length == 0){ return NULL; } TreeNode* node = new TreeNode;//Noice that [new] should be written out. node->elem = *(aftorder+length-1); std::cout<<node->elem<<std::endl; int rootIndex = 0; for(;rootIndex < length; rootIndex++)//a variation of the loop { 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 argc, char** argv){ char* af="AEFDHZMG"; char* in="ADEFGHMZ"; BinaryTreeFromOrderings(in, af, 8); printf("\n"); return 0; }