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 };
  • 相关阅读:
    线性dp 打鼹鼠
    区间dp 能量项链 洛谷p1063
    洛谷 CF1012C Hills (动态规划)
    交作业了 动态规划 木棍加工
    最短路之Floyd
    最小生成树
    寒假集训并查集初级版
    【倍增DP】——保卫王国
    bootstrap四部分概述
    zrender初识
  • 原文地址:https://www.cnblogs.com/zmlctt/p/3684007.html
Copyright © 2011-2022 走看看