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

LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-12-28 09:15:15      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:leetcode   递归   tree   中序遍历   后序遍历   

Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

这个题目的解法与LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal的解法几乎相差无几。我的C++代码实现如下:

class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        return buildTreeHelper(inorder.begin(), inorder.end(), postorder.begin(), postorder.end());
    }

    TreeNode *buildTreeHelper(vector<int> ::iterator inBegin, vector<int> ::iterator inEnd, vector<int> ::iterator postBegin, vector<int> ::iterator postEnd) {
        if (postEnd <= postBegin) return nullptr;

        TreeNode *root = new TreeNode(*(postEnd - 1));
        int leftNodes  = find(inBegin, inEnd, *(postEnd - 1)) - inBegin;
        root->left  = buildTreeHelper(inBegin, inBegin + leftNodes, postBegin, postBegin + leftNodes);
        root->right = buildTreeHelper(inBegin + leftNodes + 1, inEnd, postBegin + leftNodes, postEnd - 1);

        return root;
    }
};


时间性能如下图所示:

技术分享

LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal

标签:leetcode   递归   tree   中序遍历   后序遍历   

原文地址:http://blog.csdn.net/chfe007/article/details/42202807

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