• leetcode[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.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
    template<typename Iter>
    void creatTree(TreeNode *&root, Iter preBeg,Iter preEnd,Iter inBeg,Iter inEnd)
    {
        if (preBeg==preEnd||inBeg==inEnd)
        {
            root=NULL;
            return;
        }
        root=new TreeNode(*preBeg);
        vector<int>::iterator tmp=find(inBeg,inEnd,*preBeg);
        int leftsize=tmp-inBeg;
        creatTree(root->left, preBeg+1,preBeg+leftsize+1,inBeg,tmp);
        creatTree(root->right, preBeg+leftsize+1,preEnd,tmp+1,inEnd);
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
    {
        TreeNode *root;
        creatTree(root,preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
        return root;
    }
    /*
    TreeNode * creatTree(vector<int>::iterator preBeg,vector<int>::iterator preEnd,vector<int>::iterator inBeg,vector<int>::iterator inEnd)
    {
        if (preBeg==preEnd||inBeg==inEnd)
        {
            return NULL;
        }
        TreeNode *root=new TreeNode(*preBeg);
        vector<int>::iterator tmp=find(inBeg,inEnd,*preBeg);
        int leftsize=tmp-inBeg;
        root->left=creatTree(preBeg+1,preBeg+leftsize+1,inBeg,tmp);
        root->right=creatTree(preBeg+leftsize+1,preEnd,tmp+1,inEnd);
        return root;
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
    {
        return creatTree(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
    }
    */
    };
  • 相关阅读:
    loadrunner安装问题
    (转)经典SQL练习题
    mysql存储过程-汇总学习
    MongoDB 添加用户名和密码
    解决端口占用,查看并杀掉端口
    在 Nest.js 中使用 MongoDB 与 TypeORM
    安装 mysqlclient 报 mysql_config not found
    修改 div 的滚动条的样式
    Ubuntu 系统连接到服务器
    Python 编程入门(4):变量与赋值
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281340.html
Copyright © 2020-2023  润新知