zoukankan      html  css  js  c++  java
  • LeetCode-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.

    /**
     * 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>& postorder,int s1,int e1,int s2,int e2){
            if(s1>e1||s2>e2)return NULL;
            TreeNode* ret=new TreeNode(postorder[e2]);
            int i=s1;
            while(i<=e1){
                if(inorder[i]==postorder[e2])break;
                i++;
            }
            ret->left=Build(inorder,postorder,s1,i-1,s2,s2+i-s1-1);
            ret->right=Build(inorder,postorder,i+1,e1,s2+i-s1,e2-1);
        }
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            return Build(inorder,postorder,0,inorder.size()-1,0,inorder.size()-1);
        }
    };
    View Code
  • 相关阅读:
    struts1.2一些知识
    iText的用法
    <action里的input的作用
    CSS超链接样式常见四种状态控制
    Win7系统IIS7+Tomcat7集成
    Marquee 使用方法详解
    JAVA中String与StringBuffer的区别
    2020 8 31 每日总结
    2020 10 1
    2020 9 30
  • 原文地址:https://www.cnblogs.com/superzrx/p/3350656.html
Copyright © 2011-2022 走看看