• leetcode--Construct Binary Tree from Inorder and Postorder Traversal


    1.题目描述

    Given inorder and postorder traversal of a tree, construct the binary tree.
     
    Note:
    You may assume that duplicates do not exist in the tree.

    2.解法分析

    理解了什么是后序,什么是中序,此题迎刃而解,需要注意的是,解此题需要数组中没有相同的元素,不然的话可能性就多了。

    /**
     * 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 *buildTree(vector<int> &inorder, vector<int> &postorder) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(inorder.size()!=postorder.size()||inorder.size()==0)return NULL;
            
            return myBuildTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
            
        }
        
        TreeNode *myBuildTree(vector<int> &inorder, vector<int> &postorder,int iStart,int iEnd,int pStart,int pEnd){
            if(iStart>iEnd)return NULL;
            TreeNode *parent = new TreeNode(postorder[pEnd]);
            
            int rootIndex = iStart;
            while(inorder[rootIndex]!=postorder[pEnd]){rootIndex++;}
            parent->left = myBuildTree(inorder,postorder,iStart,rootIndex-1,pStart,pStart+rootIndex-iStart-1);
            parent->right = myBuildTree(inorder,postorder,rootIndex+1,iEnd,pEnd-(iEnd-rootIndex),pEnd-1);
            return parent;
        }
    };

    image

  • 相关阅读:
    单实例GI数据库彻底清除
    crsctl & srvctl
    Err "CLSU-00104: additional error information: need ha priv"
    Err "Kernel panic
    安装JRE
    华为-RH5885 V3 远程KVM
    Swagger与OAuth 手动搭建WebApi 操作笔记
    xib自定义View
    iOS回收键盘
    iOS设置用户头像(从相册,图库或者拍照获取)
  • 原文地址:https://www.cnblogs.com/obama/p/3258791.html
Copyright © 2020-2023  润新知