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());
        }
    };
  • 相关阅读:
    307.区域与检索--数组可修改
    202.快乐数
    263.丑数
    205.同构字符串
    204.计数质数
    40.组合总和Ⅱ
    811.子域名访问计数
    39.组合总和
    udp与tcp
    SQL复习
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5618802.html
Copyright © 2011-2022 走看看