首页 > 其他 > 详细

Construct Binary Tree From Inorder and Preorder/Postorder Traversal

时间:2014-12-20 11:39:28      阅读:227      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!