码迷,mamicode.com
首页 > 其他好文 > 详细

编程之美2: 重建二叉树

时间:2015-03-13 23:50:09      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

题目:

给定二叉树的前序队列和中序队列,构建出此二叉树。

比如

前序:

a b d c e f

后序:

d b a e c f


使用递归实现如下:

#include<stdio.h>
#include<iostream>


using namespace std;

typedef struct tagNode{
        tagNode* left;
        tagNode* right;
        char value;
} Node;

void rebuildtree(char* pPreOrder, char* pInOrder, int len, Node** root)
{
        if(len <= 0) return;
        //1: find root's value and create root Node
        char chroot = *pPreOrder;
        Node* pNode = new Node();
        pNode->left = NULL;
        pNode->right = NULL;
        pNode->value = chroot;
        *root = pNode;

        if(len == 1) return;

        //2: find root's left child and find right child
        int i = 0;
        while(i < len)
        {
                if(*(pInOrder + i) == chroot) break;
                i ++;
        }

        if(i == len) return;

        //leftchild
        rebuildtree(pPreOrder+1, pInOrder, i, &((*root)->left));
        //rightchild
        rebuildtree(pPreOrder+i+1, pInOrder+i+1, len -i -1, &((*root)->right));
}


void printTree(Node* root)
{
        if(root == NULL) return;
        printTree(root->left);
        printTree(root->right);
        cout << root->value << ",";
}
int main()
{
        char p1[7] = "abdcef";
        char p2[7] = "dbaecf";
        Node* root = NULL;
        rebuildtree(p1, p2, 6, &root);
        //end print tree
        printTree(root);
		getchar();
}



编程之美2: 重建二叉树

标签:

原文地址:http://blog.csdn.net/hhh3h/article/details/44247239

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!