zoukankan      html  css  js  c++  java
  • 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.

    Analyse: The left part of the last element of the postorder sequence in the inorder sequence is its left subtree, and the right part is the right subtree. The same as Construct Binary Tree From Preorder and Inorder Traversal.

    Runtime: 52ms.

     1 /**
     2  * Definition for a binary tree node.
     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         if(inorder.size() == 0) return NULL;
    14         return build(postorder, 0, postorder.size() - 1, inorder, 0, inorder.size() - 1);
    15     }
    16     TreeNode* build(vector<int>& postorder, int postLeft, int postRight, vector<int>& inorder, int inLeft, int inRight){
    17         if(inLeft > inRight) return NULL;
    18         
    19         TreeNode* root = new TreeNode(postorder[postRight]);
    20         if(postLeft == postRight) return root;
    21         
    22         int index;
    23         for(index = 0; index < inorder.size(); index++){
    24             if(inorder[index] == root->val) break;
    25         }
    26         root->left = build(postorder, postLeft, postLeft + index - inLeft - 1, inorder, inLeft, index - 1);
    27         root->right = build(postorder, postLeft + index - inLeft, postRight - 1, inorder, index + 1, inRight);
    28         
    29         return root;
    30     }
    31 };
  • 相关阅读:
    HDU4608+模拟
    七、cocos2dx之粒子系统
    组织机构代码校验码 验证程序
    公民身份号码 校验码 检证程序
    百度地图之短串分享
    HDU 1421 DP
    动物:黄鼬、黄鼠狼
    动物-昆虫-蜂:马蜂
    动物-昆虫-蜂:青米蜂
    动物-昆虫-蜂:土蜂
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4687502.html
Copyright © 2011-2022 走看看