leetcode 106-从中序与后序遍历序列构造二叉树

leetcode 106-从中序与后序遍历序列构造二叉树_第1张图片leetcode 106-从中序与后序遍历序列构造二叉树_第2张图片

struct TreeNode* build_Tree(int* postorder, int postorderSize, int* inorder, int inorderSize,int *root,int range1,int range2)
{
    if(*root<0)
       return NULL;
    if(range1>range2)
      return NULL;
    struct TreeNode* Root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    Root->val=postorder[*root];
    int i=0,index=0;
    for(i=range1;i<=range2;i++)
    {
        if(inorder[i]==postorder[*root])//找到根节点
        {
            index=i;
            break;
        }    
    }
    *root-=1;
    Root->right=build_Tree(postorder,postorderSize,inorder,inorderSize,root,index+1,range2);
    Root->left=build_Tree(postorder,postorderSize,inorder,inorderSize,root,range1,index-1);
    return Root;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize){
      if(postorderSize==0)//如果是一棵空树
         return NULL;
      int root=postorderSize-1;
      return build_Tree(postorder,postorderSize,inorder,inorderSize,&root,0,inorderSize-1);
}

你可能感兴趣的:(leetcode)