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

LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal

时间:2019-02-03 10:41:35      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:null   duplicate   细节   理解   follow   The   order   ||   help   

算法描述:

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

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

For example, given

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

Return the following binary tree:

    3
   /   9  20
    /     15   7

解题思路:理解原理,注意细节。

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }
    
    TreeNode* helper(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe){
        if(is > ie || ps > pe) return nullptr;
        TreeNode* node = new TreeNode(postorder[pe]);
        int pos = 0;
        for(int i=is; i <= ie; i++){
            if(postorder[pe]==inorder[i]){
                pos = i;
                break;
            }
        }
        node -> left = helper(inorder, is, pos-1, postorder, ps, ps - (is-pos+1));
        node -> right = helper(inorder, pos+1, ie, postorder, ps - (is-pos+1)+1, pe-1);
        return node;
    }

 

LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal

标签:null   duplicate   细节   理解   follow   The   order   ||   help   

原文地址:https://www.cnblogs.com/nobodywang/p/10349592.html

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