zoukankan      html  css  js  c++  java
  • 105. Construct Binary Tree from Preorder and Inorder Traversal

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

    ==============

    基本功:

    利用前序和中序构建二叉树

    ,

    ===

    code

    /**
     * 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:
        ///help_buildTree_pi()
        template<typename Iteratorr>
        TreeNode *help_buildTree_pi(Iteratorr pre_first,Iteratorr pre_last,
            Iteratorr in_first,Iteratorr in_last){
            if(pre_first == pre_last) return nullptr;
            if(in_first == in_last) return nullptr;
    
            auto root = new TreeNode(*pre_first);
            auto inRootPos = find(in_first,in_last,*pre_first);
            auto leftSize = distance(in_first,inRootPos);
    
            root->left = help_buildTree_pi(next(pre_first),next(pre_first,leftSize+1),
                                            in_first,next(in_first,leftSize));
            root->right = help_buildTree_pi(next(pre_first,leftSize+1),pre_last,next(inRootPos),in_last);
            return root;
        }
        TreeNode* buildTree_pi(vector<int> &preorder,vector<int> &inorder){
            return help_buildTree_pi(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
        }
    };
  • 相关阅读:
    Ural1387 Vasya's Dad
    SGU481 Hero of Our Time
    sjtu1590 强迫症
    sjtu1591 Count On Tree
    sjtu1585 oil
    sjtu1364 countcountcount
    sjtu1333 函数时代
    Fabric-ca client端初始化过程源码分析
    Fabric-ca server端与client端交互
    Fabric-ca server端初始化过程源码分析
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5618802.html
Copyright © 2011-2022 走看看