标签:
题目:如何根据二叉树的先序遍历和中序遍历结果还原二叉树?比如,先序遍历结果是{1,2,4,7,3,5,6,8},中序遍历结果是{4,7,2,1,5,3,8,6};
参考:http://blog.csdn.net/chdjj/article/details/37961347
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> struct BinaryTreeNode // a node in the binary tree { int m_nValue; // value of node BinaryTreeNode *m_pLeft; // left child of node BinaryTreeNode *m_pRight; // right child of node }; /*说明:T为重建的树,preorder,inorder为 前序和中序,n为长度*/ bool rebuildTree(BinaryTreeNode* &T, int *preorder, int *inorder, int n) { int i; bool flag; if (preorder==NULL || inorder==NULL) { return false; } /*注意需要判断长度,要返回真*/ if (n <= 0) { return true; } for (i=0; i<n; i++) { /*分为两部分进行处理*/ if (inorder[i] == *preorder) { break; } } if (i >= n) { return false; } T = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); T->m_nValue = *preorder; T->m_pLeft = NULL; T->m_pRight = NULL; /*递归建立左子树*/ flag = rebuildTree(T->m_pLeft, preorder+1, inorder, i); if (flag != true) { return flag; } /*递归建立右子树*/ flag = rebuildTree(T->m_pRight, preorder+i+1, inorder+i+1, n-i-1); return flag; } /*创建二叉树*/ void creatTree(BinaryTreeNode* &bTree, int *a, int pos, int len) { if (pos >= len) { bTree = NULL; return; } bTree = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); bTree->m_pLeft = NULL; bTree->m_pRight = NULL; bTree->m_nValue = a[pos]; creatTree(bTree->m_pLeft, a, 2*pos+1, len); creatTree(bTree->m_pRight, a, 2*pos+2, len); } /*先序遍历*/ void preOrderTree(BinaryTreeNode* bTree) { if (bTree == NULL) { return; } printf("%d ", bTree->m_nValue); preOrderTree(bTree->m_pLeft); preOrderTree(bTree->m_pRight); } /*中序遍历*/ void inOrderTree(BinaryTreeNode* bTree) { if (bTree == NULL) { return; } inOrderTree(bTree->m_pLeft); printf("%d ", bTree->m_nValue); inOrderTree(bTree->m_pRight); } /*后序遍历*/ void postOrderTree(BinaryTreeNode* bTree) { if (bTree == NULL) { return; } postOrderTree(bTree->m_pLeft); postOrderTree(bTree->m_pRight); printf("%d ", bTree->m_nValue); } int main() { int a[] = {1,2,4,7,3,5,6,8}; int b[] = {4,7,2,1,5,3,8,6}; BinaryTreeNode* bTree = NULL; bool flag = rebuildTree(bTree, a, b, 8); if (flag == true) { preOrderTree(bTree); } return 0; }
标签:
原文地址:http://blog.csdn.net/yuanwei1314/article/details/43740059