zoukankan      html  css  js  c++  java
  • [Leetcode 79] 106 Construct Binary Tree from Inorder and Postorder Traversal

    Problem:

    Given inorder and postorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    Analysis:

    This problem is the same as the former one of reconstructing the binary tree with inorder and preorder traversal array.

    The only difference is that now the root is always at the end of the given array.

    A comparison of the two problem's solving is as follows:

    Post & In:

    t->left = build(in, is, idx-1, post, ps, ps+idx-is-1);
    t->right = build(in, idx+1, ie, post, ps+idx-is, pe-1);

    Pre & In:

    t->left = fun(in, is, idx-1, pre, ps+1, ps+idx-is);

    t->right = fun(in, idx+1, ie, pre, ps+idx-is+1, pe);

    We can see that the sub-array for in is the same of the two solution. The difference comes from the latter part. 

    Code:

     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         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         return build(inorder, 0, inorder.size()-1, 
    16                     postorder, 0, postorder.size()-1);
    17     }
    18     
    19 private:
    20     TreeNode *build(vector<int> &in, int is, int ie,
    21                     vector<int> &post, int ps, int pe) {
    22         if (is > is || ps > pe)
    23             return NULL;
    24         
    25         TreeNode *t = new TreeNode(post[pe]);     
    26         int idx = search(in, is, ie, post[pe]);
    27 
    28         t->left = build(in, is, idx-1, post, ps, ps+idx-is-1);
    29         t->right = build(in, idx+1, ie, post, ps+idx-is, pe-1);
    30 
    31         return t;
    32     }
    33     
    34     int search(vector<int> &in, int s, int e, int v) {
    35         int idx;
    36         for (idx=s; idx<=e; idx++)
    37             if (in[idx] == v)
    38                 break;
    39                 
    40         return idx;
    41     }
    42 };
    View Code
  • 相关阅读:
    GNSS学习笔记-观测量模型和定位定速方程
    矩阵学习-基本矩阵分类
    矩阵学习-QR分解和最小二乘问题求解
    ARM 处理器 MIPS/DMIPS/MFLOPS 理解
    GNSS学习笔记-信号频率分配表
    左移右移为负数的情况
    GNSS学习笔记-坐标转换
    GCC预编译宏查看
    Windows Store无法联网时安装WSL
    Virtual box中Ubuntu虚拟机磁盘碎片整理和空间清理方法
  • 原文地址:https://www.cnblogs.com/freeneng/p/3207829.html
Copyright © 2011-2022 走看看