码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-23 09:35:14      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   中序遍历   后序遍历   构造二叉树   

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;
      }
  };



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

标签:leetcode   二叉树   中序遍历   后序遍历   构造二叉树   

原文地址:http://blog.csdn.net/hustyangju/article/details/45216761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!