根据一棵树的中序遍历与后序遍历构造二叉树。

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* _buildTree(int* inorder,int inbegin,int inend,int* postorder,int* ppostindex)
{
    //区间内没有元素
    if(inbegin > inend)
        return NULL;
    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val = postorder[*ppostindex];
    --(*ppostindex);
    
    //区间中只有一个元素
    if(inbegin == inend)
    {
        root->left = NULL;
        root->right = NULL;
        return root;
    }
    
    //区间中不止一个元素
    int rootindex = inbegin;
    while(rootindex <= inend)
    {
        if(inorder[rootindex] == root->val)
            break;
        else
            ++rootindex;
    }
    //右子树区间[rootindex+1,inend]
    root->right = _buildTree(inorder,rootindex+1,inend,postorder,ppostindex);
    //左子树区间[inbegin,rootindex-1]
    root->left = _buildTree(inorder,inbegin,rootindex-1,postorder,ppostindex);
    
    return root;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
    int postindex = postorderSize-1;
    return _buildTree(inorder,0,inorderSize-1,postorder,&postindex);   
}

猜你喜欢

转载自blog.csdn.net/chenxiyuehh/article/details/86018737
今日推荐