重构二叉树

重构二叉树的思路主要是首先在前序(后序)序列中找到根结点,然后在中序序列中找到根结点所在的位置,该结点将整个序列分成两个部分,前一部分为根结点的左子树元素,后一部分为根结点的右子树元素。再递归的生成左子树和右子树即可。

1.通过前序,中序序列重构二叉树

TreeNode * buildTree(vector<int>& preorder, int preBegin, int preEnd, vector<int>& inorder, int inBegin, int inEnd)
 {
    TreeNode*root =NULL;

    if (preEnd >= preBegin)
    {
        root = new TreeNode(preorder[preBegin]);
        int rootIndex = 0;
        for (int i = inBegin; i <= inEnd; ++i)
        {
            if (inorder[i] == preorder[preBegin])
            {
                rootIndex = i;
                break;
            }
        }

        if (rootIndex!=inBegin)
        {
            root->left = buildTree(preorder, preBegin+1, preBegin+(rootIndex-inBegin), inorder, inBegin, rootIndex-1);
        }
        if (rootIndex!=inEnd)
        {
            root->right = buildTree(preorder, preBegin+1+(rootIndex-inBegin), preEnd, inorder, rootIndex+1, inEnd);
        }
    }
    return root;  
 }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }

 

2.通过中序,后序序列重构二叉树

TreeNode * buildTree(vector<int>& inorder, int inBegin, int inEnd, vector<int>& postorder, int postBegin, int postEnd)
 {
    TreeNode*root =NULL;

    if (postEnd >= postBegin)
    {
        root = new TreeNode(postorder[postEnd]);

        int rootIndex = 0;
        for (int i = inBegin; i <= inEnd; ++i)
        {
            if (inorder[i] == postorder[postEnd])
            {
                rootIndex = i;
                break;
            }
        }

        if (rootIndex!=inBegin)
        {
            root->left = buildTree( inorder, inBegin, rootIndex-1, postorder, postBegin, postBegin+(rootIndex-inBegin)-1);
        }
        if (rootIndex!=inEnd)
        {
            root->right = buildTree(inorder, rootIndex+1, inEnd, postorder, postBegin+(rootIndex-inBegin), postEnd-1);
        }
    }
    return root;  
 }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
      return buildTree(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);  
    }

 

posted @ 2015-05-19 14:50  Rosanne  阅读(325)  评论(0编辑  收藏  举报