zoukankan      html  css  js  c++  java
  • LeetCode-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:
        TreeNode* Build(vector<int>& inorder,vector<int>& preorder,int s1,int e1,int s2,int e2){
            if(s1>e1||s2>e2)return NULL;
            TreeNode* ret=new TreeNode(preorder[s2]);
            int i=s1;
            while(i<=e1){
                if(inorder[i]==preorder[s2])break;
                i++;
            }
            ret->left=Build(inorder,preorder,s1,i-1,s2+1,s2+i-s1);
            ret->right=Build(inorder,preorder,i+1,e1,s2+i-s1+1,e2);
        }
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            return Build(inorder,preorder,0,inorder.size()-1,0,inorder.size()-1);
        }
    };
    View Code
  • 相关阅读:
    20210608日报
    数据结构-四则表达式运算
    软工博客归档工具(自用)
    阅读笔记6
    阅读笔记4
    阅读笔记3
    阅读笔记2
    阅读笔记5
    阅读笔记1
    大二下第16周总结
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350730.html
Copyright © 2011-2022 走看看