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

Construct Binary Tree From Inorder and Preorder/Postorder Traversal

时间:2014-12-20 11:40:02      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

map<int, int> mapIndex;
void mapToIndex(int inorder[], int n)
{
    for (int i = 0; i < n; i++)
    {
        mapIndex.insert(map<int, int>::value_type(inorder[i], i);
    }
}

Node* buildInorderPreorder(int in[], int pre[], int n, int offset)
{
    assert(n >= 0);
    if (n == 0)
        return NULL;
    int rootVal = pre[0];
    int i = mapIndex[rootVal] - offset;
    Node* root = new Node(rootVal);
    root->left = buildInorderPreorder(in, pre+1, i, offset);
    root->right = buildInorderPreorder(in+i+1, pre+i+1, n-i-1, offset+i+1);
    return root;
}

Node* buildInorderPostorder(int in[], int post[], int n, int offset)
{
    assert(n >= 0);
    if (n == 0)
        return NULL;
    int rootVal = post[n-1];
    int i = mapIndex[rootVal] - offset;
    Node* root = new Node(rootVal);
    root->left = buildInorderPostorder(in, post, i, offset);
    root->right = buildINorderPostorder(in+i+1, post+i, n-i-1, offset+i+1);
    return root;
}

 

Construct Binary Tree From Inorder and Preorder/Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/litao-tech/p/4175172.html

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