1 // 类定义代码 2 struct TreeNode 3 { 4 char val; 5 TreeNode* left; 6 TreeNode* right; 7 TreeNode(char x) : val(x), left(NULL), right(NULL) {} 8 }; 9 int main() 10 { 11 char* pre = "ACDEBF"; 12 char* vin = "DCEABF"; 13 char* post = "DECFBA"; 14 return 0; 15 }
算法思想:描述如下:
递归代码:
1 TreeNode* BinaryTreeFromOrderings(char* pre, char* vin, int length) 2 { 3 if( length == 0 ) return NULL; 4 5 int rootIndex = 0; 6 // 寻找当前根节点,记录子树元素个数 7 for(; rootIndex < length; rootIndex ++) 8 if( vin[rootIndex] == pre[0] ) break; 9 10 TreeNode* tree = new TreeNode( vin[rootIndex] ); 11 // 返回当前左子树 12 tree ->left = BinaryTreeFromOrderings(pre + 1, vin, rootIndex ); 13 // 返回当前右子树 14 tree ->right = BinaryTreeFromOrderings(pre + rootIndex + 1, vin + rootIndex + 1, length - (rootIndex + 1)); 15 16 return tree; 17 }
算法思想:描述如下:
递归代码:
TreeNode* BinaryTreeFromPostings(char* vin, char* post, int length) { if( length == 0 ) return NULL; int rootIndex = 0; // 寻找当前根节点,记录子树元素个数 for(; rootIndex < length; rootIndex ++) if( vin[rootIndex] == post[length - 1]) break; TreeNode* tree = new TreeNode( vin[rootIndex] ); // 返回当前右子树 tree ->right = BinaryTreeFromPostings(vin + rootIndex + 1, post + rootIndex, length - (rootIndex + 1) ); // 返回当前左子树 tree ->left = BinaryTreeFromPostings(vin, post, rootIndex ); return tree; }
已知前序和中序,后序和中序遍历序列之后,可以唯一确定一棵二叉树。但是,只知道前序和后序遍历序列,是无法分辨哪个结点是左子树或右子树。
原文:https://www.cnblogs.com/john1015/p/12906507.html