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

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

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

     

    Subscribe to see which companies asked this question

     
     
    递归就可以了。
     
    #include<algorithm>
    using namespace std;
    /**
     * 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:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            if(preorder.size()==0||inorder.size()==0||find(inorder.begin(),inorder.end(),preorder[0])==inorder.end())
                return NULL;
            auto rootindex=find(inorder.begin(),inorder.end(),preorder[0]);
            TreeNode *root = new TreeNode(preorder[0]);
            vector<int> subleft,subright;
            preorder.erase(preorder.begin());
            if(rootindex!=inorder.begin())
                subleft.insert(subleft.begin(),inorder.begin(),rootindex);
            if(rootindex!=inorder.end()-1)
                subright.insert(subright.begin(),rootindex+1,inorder.end());
               root->left=buildTree(preorder,subleft);
               root->right=buildTree(preorder,subright);
               return root;
        }
    };
  • 相关阅读:
    魔法阵
    求和
    罗马数字
    「NOIP2005P」循环
    【Windows批处理III】实现删除含自定字符串的文件和文件夹(搜索子目录)
    扩展欧几里得算法
    埃氏筛法(素数筛)
    python学习之argparse模块
    51Nod1364 最大字典序排列
    51Nod1537 分解
  • 原文地址:https://www.cnblogs.com/LUO77/p/5616963.html
Copyright © 2011-2022 走看看