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;
            
            
        }
    };
  • 相关阅读:
    H5基础
    函数
    分支结构/循环结构
    图解 idea打jar包的步骤
    jmeter查看使用文档后总结
    Ride的使用
    Robot Framework
    jmeter+ant+jenkins
    ant
    Mysql选择合适的数据类型
  • 原文地址:https://www.cnblogs.com/dacc123/p/9218959.html
Copyright © 2011-2022 走看看