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;
        }
    };
    
  • 相关阅读:
    css display和vertical-align 属性
    Python:time模块/random模块/os模块/sys模块
    css display和vertical-align 属性
    初始面向对象
    模块小记
    迭代器与生成器
    默认参数的陷阱自我心得
    初始函数
    文件操作
    python基础知识补充
  • 原文地址:https://www.cnblogs.com/UniMilky/p/7015713.html
Copyright © 2011-2022 走看看