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.

    常规方法,以中序为主,在中序中查找根,划分成左右两部分递归,注意要记录左部分个数,后续遍历找根需要,这里没有考虑不能建成树的情况

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    13         int m=inorder.size();
    14         int n=postorder.size();
    15         if(m==0||n==0||m!=n) return NULL;     //如果m,n不等,一定不对
    16         
    17         return build(inorder,0,n-1,postorder,0,n-1);
    18       
    19     }
    20     TreeNode * build(vector<int> & inorder,int inl,int inr,vector<int> &postorder,int pol,int por)
    21     {
    22 
    23         if(inl>inr)
    24         {
    25             return NULL;
    26         }
    27         int value=postorder[por];
    28         TreeNode * root=new TreeNode(value);
    29         int i;
    30         int count=0;                             //记录左部分个数                     
    31         for(i=inl;i<=inr;i++)
    32         {
    33             if(inorder[i]==value)
    34             {
    35                 break;
    36             }
    37             count++;
    38         }
    39         root->left=build(inorder,inl,i-1,postorder,pol,pol+count-1);                   //注意count-1
    40         root->right=build(inorder,i+1,inr,postorder,pol+count,por-1);
    41         return root;
    42         
    43     }
    44 };
  • 相关阅读:
    sql2000/2005获取表的列SQL文
    SQL Server未公开的两个存储过程
    HNOI2008 玩具装箱
    noi2004 郁闷的出纳员
    狼抓兔子(平面图转对偶图求最短路)
    pku1917 Automatic Poetry
    幸福的道路
    闲话电子商店(eshop)的设计和经营2
    基金清仓,晚上欢聚
    早上想来想去,把自己的基金卖了1/5
  • 原文地址:https://www.cnblogs.com/zmlctt/p/3684007.html
Copyright © 2011-2022 走看看