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

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

题目描述

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

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

例如,给出

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

返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

解题思路

在前序、中序、后序三个序列中,能够完成一个二叉树重建的包括前序、中序,中序、后序;意思是三个序列要构造一个二叉树必须包括中序遍历。在中序和后序构造二叉树的过程中,postorder序列的最后一个节点就是根节点,根据根节点可以在中序中找到左右子树,那该题举例子,postorder=[9,15,7,20,3],inorder=[9,3,15,20,7],那么3就是根节点,根据postorder中的根节点3,可在inorder中找到左右子树的元素,左子树inorderLeft为[9],inorderRight右子树为[15,20,7],然后再把postorder分成左右子树,左子树postorderLeft[9],右子树postorderRight[15,7,20],同样的继续这样的操作,找到左右子树的根节点,一直到空,就可构建整个二叉树。代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        // 序列是否为空
        if(inorder.size() == 0 || postorder.size() == 0){
            return NULL;
        }

        return build(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }

    /*
    * 递归函数
    */
    TreeNode* build(vector<int>& inorder, int inL, int inR, vector<int>& postorder, int postL, int postR){
        // 如果中序的左侧下标超过右侧下标,那么结束递归
        if(inL > inR){
            return NULL;
        }
		// 定义根节点,根节点为每个后序的最后一个位置,即右侧下标对应的元素
        TreeNode* root = new TreeNode(postorder[postR]);
        
        int index = inL; // 查找后序最右侧的元素在中序中的位置
        while(inL <= inR && inorder[index] != postorder[postR]){
            index++;
        }
        int len = index - inL; // 计算长度,根据长度可以拆分左右子树
        // 左子树
        root->left = build(inorder, inL, inL+len-1, postorder, postL, postL+len-1); 
        // 右子树
        root->right = build(inorder, inL+len+1, inR, postorder, postL+len, postR-1);

        return root;
    }
};

欢迎大家关注我的个人公众号,同样的也是和该博客账号一样,专注分享技术问题,我们一起学习进步
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值