赞
踩
struct TreeNode { char data; TreeNode* lchild; TreeNode* rchild; }; //#号法创建树 先序创建 TreeNode* createTree() { TreeNode* node = NULL; TreeNode* pL = NULL; TreeNode* pR = NULL; char h; scanf("%c", &h); cout << "h: " << h << endl; if (h == '#') { return NULL; } else { node = new TreeNode; memset(node, 0, sizeof(TreeNode)); node->data = h; pL = createTree(); if (pL != NULL) { node->lchild = pL; cout << "pL data: " << pL->data << endl;; } else { node->lchild = NULL; cout << "pL data: NULL" << endl;; } pR = createTree(); if (pR != NULL) { node->rchild = pR; cout << "pR data: " << pR->data << endl;; } else { node->rchild = NULL; cout << "pR data: NULL" << endl;; } } return node; } //先序创建树 用后序释放 void deleteTree(TreeNode* node) { if (node == NULL) { return ; } if (node->lchild != NULL) { deleteTree(node->lchild); node->lchild = NULL; } if (node->rchild != NULL) { deleteTree(node->rchild); node->rchild = NULL; } if (node != NULL) { deleteTree(node); node == NULL; } } void preMethood(TreeNode* root) { if (root == NULL) { return; } cout << " preMethood: " << root->data << " "; preMethood(root->lchild); preMethood(root->rchild); } /* 先序遍历和中序遍历生成树 1.通过先序遍历找到根节点A,再通过中序遍历的位置找出左子树,右子树 2.在A的左子树中,找左子树的根节点(在先序遍历中找),转1 3.在A的右子树中,找右子树的根节点(在先序遍历中找),转1 先序遍历:ADEBCF 中序遍历:DEACFB */ TreeNode* createTreeByPreAndMed(char* pre, char* med, int length) { TreeNode* node = new TreeNode; node->data = pre[0]; node->lchild = NULL; node->rchild = NULL; cout << "crtdata: " << node->data << endl; if (length == 0) { return NULL; } if (length == 1) { return node; } char data[2] = { pre[0],'\0' }; char* finddata = strstr(med, data); int len = finddata - med; cout << "findleft: " << pre + 1 << endl; node->lchild = createTreeByPreAndMed(pre + 1, med, len); cout << " findright: " << pre + len + 1 << endl; node->rchild = createTreeByPreAndMed(pre + len + 1, med + len + 1, length - len - 1); cout << "crtdata: " << node->data << " lchild: " << node->lchild->data << " rchild: " << node->rchild->data << endl; return node; } int main() { char* str1 = "124895367"; char* str2 = "849251637"; createTreeByPreAndMed(str1, str2, strlen(str1)); system("pause"); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。