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.

    方法:在inorder中寻找postorder的最后一个,然后左右递归,注意处理好各个low,high边界

     1 class Solution
     2 {
     3     public:
     4         TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
     5         {
     6             return buildTree(postorder, 0, postorder.size()-1,
     7                               inorder, 0, inorder.size()-1);
     8         }
     9 
    10         TreeNode *buildTree(vector<int> &postorder, int low1, int high1,
    11                             vector<int> &inorder, int low2, int high2)
    12         {
    13             //cout << "==============" <<endl;
    14             //cout << "low1 = 	" << low1 <<endl;
    15             //cout << "high1= 	" << high1 <<endl;
    16             //cout << "low2 = 	" << low2 <<endl;
    17             //cout << "high2= 	" << high2 <<endl;
    18             if(low1 > high1 || low2> high2)
    19                 return NULL;
    20 
    21             TreeNode * p = new TreeNode(postorder[high1]);
    22             if(low1 == high1)
    23             {   
    24                 return p;
    25             }   
    26             int index = 0;
    27             for(index = low2; index < high2; index++)
    28             {   
    29                 if(inorder[index] == postorder[high1])
    30                     break;
    31             }   
    32             //cout << "index= 	" << index<<endl;
    33 
    34             if(index != low2)
    35                 p->left = buildTree(postorder, low1,(low1) + (index-1-low2), inorder, low2, index-1);
    36             if(index != high2)
    37                 p->right = buildTree(postorder, (high1-1) - (high2-index-1) ,high1-1, inorder, index+1, high2);
    38 
    39             return p;
    40         }
    41 } ;
  • 相关阅读:
    服务注册中心之Eureka使用
    微服务之服务注册中心
    Idea热部署功能
    微服务Cloud整体聚合工程创建过程
    微服务架构理论&SpringCloud
    关于母函数
    HDU 1028(母函数)整数划分
    1021 FIBERNACI
    1019
    1014 巧妙的gcd 生成元
  • 原文地址:https://www.cnblogs.com/diegodu/p/3812790.html
Copyright © 2011-2022 走看看