106. Construct Binary Tree from Inorder and Postorder Traversal(Tree)

链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题目:给定二叉树中序和后序遍历,构造出原二叉树。

思路:
根节点在后序遍历的最后一个位置,在中序遍历的中间位置。通过后序遍历找到根节点,然后通过中序遍历找出左右子树,然后递归构造。例如给定样例:

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

                                    inorder, postorder 
                               [9,3,15,20,7] , [9,15,7,20,3]  ,根节点:3
    inorder , postorder (左子树)                         inorder ,postorder(右子树)
       [9]  ,[9]  ,根节点:9                                [15,20,7] , [15,7,20],根节点:20
                                          inorder , postorder (左子树)       inorder ,postorder(右子树)
                                            [15] ,[15] ,根节点:15                 [7] ,[7] ,根节点:7


最终结果:

    3
   / \
  9  20
    /  \
   15   7

代码:

class Solution {
public:
    TreeNode* build(vector<int>& inorder, vector<int>& postorder,int il , int ir ,int pl, int pr){
              if(il > ir) return NULL;
        
              int i = il;
        
              while(inorder[i]!=postorder[pr]) i++;
        
              TreeNode* cur = new TreeNode(postorder[pr]);
        
              cur->left = build(inorder, postorder,il , i-1 ,pl, pl + i - il - 1);
              cur->right = build(inorder, postorder,i+1 , ir ,pl + i - il , pr-1);
        
              return cur;
    }
    
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
              return build(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

计算机的小粽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值