zoukankan      html  css  js  c++  java
  • LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树 C++

    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

    中序、后序遍历得到二叉树,可以知道每一次新数组的最后一个数为当时子树的根节点,每次根据中序遍历的根节点的左右两边确定左右子树,再对应后序的左右子树,不停递归得到根节点,可以建立二叉树。每次由循环得到根节点在中序数组中坐标i

    由中序遍历知:每一次inorder的左子树范围[ileft,i-1],右子树范围[i+1,iright]

    由后序遍历知:每一次postorder的左子树范围[pleft,pleft+i-ileft-1],右子树范围[pleft+i-ileft,pright-1]。C++

     1 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
     2         return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
     3     }
     4     
     5     TreeNode* buildTree(vector<int>& inorder,int ileft,int iright,vector<int>& postorder,int pleft,int pright){
     6         if(ileft>iright||pleft>pright)
     7             return NULL;
     8         TreeNode* root=new TreeNode(postorder[pright]);
     9         int i=0;
    10         for(i=ileft;i<=iright;i++){
    11             if(inorder[i]==postorder[pright])
    12                 break;
    13         }
    14         root->left=buildTree(inorder,ileft,i-1,postorder,pleft,pleft+i-ileft-1);
    15         root->right=buildTree(inorder,i+1,iright,postorder,pleft+i-ileft,pright-1);
    16         return root;
    17     }
  • 相关阅读:
    Microsoft training Kits
    WCF Load Test
    SQL Server Central Management System
    连贯NHibernate 1.0正式发布
    C#全角和半角转换
    Silverlight 2应用所采用的WCF技术
    实用工具特别推荐 Robocopy GUI
    SmtpClient发送邮件遭遇The specified string is not in the form required for a subject.
    SQL Server 2008使用扩展事件进行高级故障排除
    Visual Studio 2010新特性
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10713560.html
Copyright © 2011-2022 走看看