码迷,mamicode.com
首页 > 编程语言 > 详细

Construct Binary Tree from Inorder and Postorder Traversal (算法课上的题)

时间:2015-08-26 22:13:40      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

Construct Binary Tree from Inorder and Postorder Traversal

这道题之前算法课上好像遇到过,思路也很简单的。

思路:后序序列的最后一个元素就是树根,然后在中序序列中找到这个元素(由于题目保证没有相同的元素,因此可以唯一找到),中序序列中这个元素的左边就是左子树的中序,右边就是右子树的中序,然后根据刚才中序序列中左右子树的元素个数可以在后序序列中找到左右子树的后序序列,然后递归的求解即可。(在去除了根节点之后,中序遍历和后序遍历的前N个树都是左子树,有了这个前提之后,代码也就好写了。)

特别注意的是:之前提到过,每当涉及到树,就应该考虑到递归能不能用。

/**
 * 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:
       typedef vector<int>::iterator Iter;
       TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
           // IMPORTANT: Please reset any member data you declared, as
           // the same Solution instance will be reused for each test case.
           return buildTreeRecur(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
       }
       TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend)
       {
           if(istart == iend)return NULL;
           int rootval = *(pend-1);
           Iter iterroot = find(istart, iend, rootval);
           TreeNode *res = new TreeNode(rootval);
           res->left = buildTreeRecur(istart, iterroot, pstart, pstart+(iterroot-istart));
           res->right = buildTreeRecur(iterroot+1, iend, pstart+(iterroot-istart), pend-1);
           return res;
    }
};

 

Construct Binary Tree from Preorder and Inorder Traversal

  同上,只是树根是先序序列的第一个元素

 

/**
 * 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:
     typedef vector<int>::iterator Iter;
     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
         // IMPORTANT: Please reset any member data you declared, as
         // the same Solution instance will be reused for each test case.
         return buildTreeRecur(inorder.begin(), inorder.end(), preorder.begin(), preorder.end());
     }
     TreeNode *buildTreeRecur(Iter istart, Iter iend, Iter pstart, Iter pend)
     {
         if(istart == iend)return NULL;
         int rootval = *pstart;
         Iter iterroot = find(istart, iend, rootval);
         TreeNode *res = new TreeNode(rootval);
         res->left = buildTreeRecur(istart, iterroot, pstart+1, pstart+1+(iterroot-istart));
         res->right = buildTreeRecur(iterroot+1, iend, pstart+1+(iterroot-istart), pend);
         return res;
     }
};

  

Construct Binary Tree from Inorder and Postorder Traversal (算法课上的题)

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4761722.html

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