根据二叉树的前序数组和中序数组生成二叉树

来源:互联网 发布:聂卫平与高层关系 知乎 编辑:程序博客网 时间:2024/04/29 07:24
typedef struct NodeType{   int data;   struct NodeType* left;   struct NodeType* right;   NodeType(){left = NULL;right = NULL;};}Node;/** parameter arr_pre, preorder array of tree* parameter size_pre, size of preorder array* parameter arr, order array of tree* parameter size, size of order array** Traverse order array of binary tree to construct a binary tree(遍历中序数组来构建二叉树)*/NodeType* BuildTree(NodeType* arr_pre, int size_pre, NodeType* arr, int size){    if ( 0 == size)  return NULL;    Node* sub_root = NULL;    int root_index_in_arr = 0;    bool is_found = false;    for (int i = 0;(i < size_pre) && (!is_found);i++) {        int data = (arr_pre + i)->data;        for (int j = 0;j < size;j++) {            if (data == (arr + j)->data) {                sub_root = arr + j;                root_index_in_arr = j;                is_found = true;                break;            }        }    }    sub_root->left =  BuildTree(arr_pre, size_pre, arr, root_index_in_arr); //Left subtree    sub_root->right = BuildTree(arr_pre, size_pre, arr + root_index_in_arr + 1, size - root_index_in_arr - 1); //Right subtree    return sub_root;}//Traverse in postorder(后续遍历输出)void PrintPostorder(NodeType* root){    if (NULL != root) {        PrintPostorder(root->left);        PrintPostorder(root->right);        cout << (char) root->data << endl;    }}void SearchRelatedNodes(NodeType* root, int value, NodeType* parent){    if (NULL != root) {        if (root->data == value) {            if (NULL != parent) {                cout << "Parent is : " << (char) parent->data << endl;            } else {                cout << "Parent is : NULL" << endl;            }            if (NULL != root->left) {                cout << "left son is : " << (char) root->left->data << endl;            } else {                cout << "left son is : NULL" << endl;            }            if (NULL != root->right) {                cout << "right son is : " << (char) root->right->data << endl;            } else {                cout << "right son is : NULL" << endl;            }        }        parent = root;        SearchRelatedNodes(root->left, value, parent);        SearchRelatedNodes(root->right, value, parent);    }}int _tmain(int argc, _TCHAR* argv[]){    NodeType tmp;    tmp.data = 'a';    NodeType tmp1;    tmp1.data = 'b';    NodeType tmp2;    tmp2.data = 'd';    NodeType tmp3;    tmp3.data = 'e';    NodeType tmp4;    tmp4.data = 'h';    NodeType tmp5;    tmp5.data = 'c';    NodeType tmp6;    tmp6.data = 'f';    NodeType tmp7;    tmp7.data = 'g';                //Preorder: abdehcfg        //Order: dbehafcg    NodeType pre[8] = {tmp,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7};   //Preorder array(前序遍历数组)    NodeType order[8] = {tmp2,tmp1,tmp3,tmp4,tmp,tmp6,tmp5,tmp7}; //Order array(中序遍历数组)    NodeType* root =  BuildTree(pre, 8, order, 8);    PrintPostorder(root);    SearchRelatedNodes(root, 'c', NULL);}


0 0
原创粉丝点击