• 105.Construct Binary Tree from Preorder and Inorder Traversal


    思路:
    • 递归。
    /**
     * 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) {
            return Construct(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
        }
        TreeNode *Construct(vector<int>& preorder,int s0,int e0,vector<int>& inorder,int s1,int e1){
            if(s0 > e0 || s1 > e1)  return NULL;
            int rootval = preorder[s0];
            int rootindex = find(inorder,s1,e1,rootval);
            TreeNode* root = new TreeNode(rootval);
            int leftsize = rootindex - s1 + 1;
            
            root->left = Construct(preorder,s0+1,s0+leftsize-1,inorder,s1,rootindex-1);
            root->right = Construct(preorder,s0+leftsize,e0,inorder,rootindex+1,e1);
            return root;
        }
        int find(vector<int>& inorder,int s1,int e1,int rootval){
            for(int i = s1; i <= e1; i++){
                if(inorder[i] == rootval) return i;
            }
            return -1;
        }
    };
    
  • 相关阅读:
    python CreateUniqueName()创建唯一的名字
    node 创建静态服务器并自动打开浏览器
    基于jQuery 的插件开发
    Fetch
    纯css 来实现下拉菜单
    javascript模板引擎之
    jquery jsonp 跨域
    数据库增删改查
    Promise
    Vue.js
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7015713.html
Copyright © 2020-2023  润新知