• LeetCode OJ--Construct Binary Tree from Inorder and Postorder Traversal *


    http://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

    知道二叉树的中序遍历和后序遍历序列,求二叉树。

    使用递归

    #include <iostream>
    #include <vector>
    using namespace std;
    
     struct TreeNode {
         int val;
         TreeNode *left;
         TreeNode *right;
         TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     };
    
     
    class Solution{
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
        {
            return buildTree(begin(inorder),end(inorder),begin(postorder),end(postorder));
        }
        template<typename BidiIt>
        TreeNode* buildTree(BidiIt in_first, BidiIt in_last,BidiIt post_first,BidiIt post_last)
        {
            if(in_first ==in_last) 
                return nullptr;
            if(post_first == post_last)
                return nullptr;
            const auto val = *prev(post_last);
            TreeNode* root = new TreeNode(val);
    
            auto in_root_pos = find(in_first,in_last,val);
            auto left_size = distance(in_first,in_root_pos);
            auto post_left_last = next(post_first,left_size);
    
            root->left = buildTree(in_first,in_root_pos,post_first,post_left_last);
            root->right = buildTree(next(in_root_pos),in_last,post_left_last,prev(post_last));
            return root;
        }
    };
    
    int main()
    {
        Solution myS;
        int arr1[7] = {4,2};//,5,1,6,3,7 };
        int arr2[7] = {4,2};//,2,6,7,3,1 };
        vector<int> inorder(arr1,arr1+2) ;
        vector<int> postorder(arr2 ,arr2+2);
        TreeNode *myNode;
    
        myNode = myS.buildTree(inorder,postorder);
         
        cout<<"hi"<<endl;
        return 0;
    }
  • 相关阅读:
    【hihocoder 1477】闰秒
    【codeforces 768F】Barrels and boxes
    【codeforces 767E】Change-free
    【codeforces 810A】Straight «A»
    【codeforces 810B】Summer sell-off
    【codeforces 810C】Do you want a date?
    【codeforces 757E】Bash Plays with Functions
    【codeforces 749D】Leaving Auction
    Java数据结构与算法(5)
    使用Xshell远程连接管理Linux实践
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3694881.html
Copyright © 2020-2023  润新知