leetcode || 106、Construct Binary Tree from Inorder and Postorder Traversal

本文详细介绍了如何使用中序和后续遍历序列构建二叉树,通过实例展示了构建过程,并提供了相应的代码实现。

problem:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Hide Tags
  Tree Array Depth-first Search
题意:给定二叉树的中序遍历序列和后续遍历序列,构建这棵二叉树,也很经典

thinking:

(1)这种类型的题,要举个例子找出其规律。对于满二叉树(1,2,3,4,5,6,7),中序遍历:4,2,5,1,6,3,7  后续遍历:4,5,2,6,7,3,1

首先根结点1在后续遍历序列的最后一个位置上,再在中序遍历序列中find 1的位置,1之前的为左子树,1 之后的为右子树。知道子树节点数量后,

同样对于后续遍历序列也可以划分左右子树。

(2)递归重复上述过程

code:

class Solution {
  public:
      TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
          if (inorder.size() == 0)
              return NULL;
          return make(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());    
      }
  protected:
      template<class it>
      TreeNode *make(it pFirst,it pLast,it qFirst,it qLast)
      {
          if(pFirst==pLast)
              return NULL;
          it loc1 = qLast-1;
          int a = *loc1;
          it loc2=find(pFirst,pLast,a);
          int left_size=loc2-pFirst;
          TreeNode *root=new TreeNode(a);
          root->left=make(pFirst,loc2,qFirst,qFirst+left_size);
          root->right=make(loc2+1,pLast,qFirst+left_size,qLast-1);
          return root;
      }
  };



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值