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.

    /**
     * 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>&pre,int prestart,int preend,vector<int>&in,int instart,int inend)
        {
            if(preend<prestart||inend<instart||(preend-prestart)!=(inend-instart))
                return NULL;
            TreeNode *head = new TreeNode(pre[prestart]);
            int rootpos;
            for(int i=0;i<=inend-instart;i++)
                if(in[i+instart]==pre[prestart])
                {
                    rootpos = i;
                    break;
                }
                
            head->left = build(pre,prestart+1,prestart+rootpos,in,instart,instart+rootpos-1);
            head->right = build(pre,prestart+rootpos+1,preend,in,instart+rootpos+1,inend);
            return head;
        }
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
        {
            int presize = preorder.size();
            int insize   = inorder.size();
            TreeNode *head = build(preorder,0,presize-1,inorder,0,insize-1);
            return head;
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    软件工程结对作业02
    最大子数组和
    四则运算2单元测试
    软件工程个人作业03
    梦断代码阅读笔记01
    最大值的单元测试
    构建之法阅读笔记01
    进度条记录02
    软件工程个人作业02
    【BZOJ2595_洛谷4294】[WC2008]游览计划(斯坦纳树_状压DP)
  • 原文地址:https://www.cnblogs.com/vintion/p/4116859.html
Copyright © 2011-2022 走看看