zoukankan      html  css  js  c++  java
  • LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    For example, given

    inorder = [9,3,15,20,7]
    postorder = [9,15,7,20,3]

    Return the following binary tree:

        3
       / 
      9  20
        /  
       15   7


    和105一样,稍微改一下就好了、
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            
            vector<int> leftpost;
            vector<int> leftino;
            vector<int> rightpost;
            vector<int> rightino;
            
            if(postorder.empty()||inorder.empty())
                return NULL;
            int root = postorder[postorder.size()-1]; int left=0;int right=0;int tag=0;
            for(int i=0;i<inorder.size();i++)
            {
                if(inorder[i]==root)
                {
                    tag=1;
                }
                else if(tag==0)
                {left++;leftino.push_back(inorder[i]);}
                else
                {right++;rightino.push_back(inorder[i]);}
            }
            for(int i=0;i<left;i++)
            {
                leftpost.push_back(postorder[i]);
            }
            for(int i=left;i<postorder.size()-1;i++)
            {
                rightpost.push_back(postorder[i]);
            }
            
            TreeNode* tree = new TreeNode(root);
           
            tree->left = buildTree(leftino,leftpost);
            tree->right = buildTree(rightino,rightpost);
            
            return tree;
            
            
        }
    };
  • 相关阅读:
    转 UICollectionView 详解
    springboot配置ssl证书
    服务器ganglia安装(带有登录验证)
    eureka配置说明
    Servlet中获取请求参数问题
    apidoc学习(接口文档定义取代word)
    markdown语法
    JVM分析
    ftp上传或下载文件工具类
    ubuntu命令安装
  • 原文地址:https://www.cnblogs.com/dacc123/p/9218959.html
Copyright © 2011-2022 走看看