zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    jsp 页面获取当前路径
    html5 页面音频
    微信关于网页授权access_token和普通access_token的区别
    Texlive source
    vscode 快捷键
    vscode setting
    vscode extension 插件管理
    what
    linux manual
    java tool type
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7015713.html
Copyright © 2011-2022 走看看