【二叉树还原】已知后序和中序还原二叉树

leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal

一、问题描述

给定树的中序遍历和后序遍历,构造二叉树。假定树中不存在重复项
中序 = [9,3,15,20,7]
后序 = [9,15,7,20,3]
返回下列二叉树:
    3
   / \
  9  20
    /  \
   15   7

二、解题思路

二叉树

        后序遍历:左右根  --- 9,3,15,20,7

        中序遍历:左根右 --- 9,15,7,20,3

    所以,后序遍历最后一个元素一定是根节点->在中序遍历中找该元素所在位置,则该元素左边就是该根节点左子树部分,右边就是该根节点右子树部分->再分别对这两个部分递归做相同算法。

三、算法实现

/*********************************************
Author:tmw
date:2018-5-8
*********************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode
{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
}TreeNode;

/**在中序遍历中找根节点所在位置,返回位置下标**/
int find_root_index( int* inorder, int inorderLeft, int inorderRight, int root_elem )
{
    if( !inorder || inorderLeft<0 || inorderLeft>inorderRight )
        return -1;
    int i;
    for( i=inorderLeft; i<=inorderRight; i++ )
        if( inorder[i] == root_elem )
            return i;
    return -1;
}

/**找到根节点**/
TreeNode* getRoot( int* inorder, int in_left, int in_right, int* postorder, int post_left, int post_right )
{
    /**参数合法性判断**/
    if( !inorder || !postorder ) return NULL;
    if( in_left<0 || in_right<in_left ) return NULL;
    if( post_left<0 || post_right<post_left ) return NULL;

    /**通过后序找到根节点,并给它分配空间**/
    int rootElem = postorder[post_right];
    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    root->val = rootElem;
    root->left = NULL;
    root->right = NULL;

    /**找到根节点在中序中的下标**/
    int root_index = find_root_index(inorder,in_left,in_right,rootElem);
    if( root_index == -1 ) return NULL;

    /**递归求左子树**/
    root->left = getRoot(inorder,in_left,root_index-1,postorder,post_left,post_left+root_index-in_left-1);
    /**递归求右子树**/
    root->right = getRoot(inorder,root_index+1,in_right,postorder,post_left+root_index-in_left,post_right-1);
    return root;
}

TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize)
{
    if( !inorder || !postorder ) return NULL;
    return getRoot(inorder,0,inorderSize-1,postorder,0,postorderSize-1);
}

四、执行结果

accpet


梦想还是要有的,万一实现了呢~~~ヾ(◍°∇°◍)ノ゙~~~


  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值