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         if (inorder.empty() || postorder.empty())
    14             return NULL;
    15             return buildTree(inorder.begin(), inorder.end() - 1, postorder.begin(), postorder.end() - 1);
    16         }
    17     template<typename Iter>
    18     TreeNode* buildTree(Iter inBegin, Iter inEnd, Iter postBegin, Iter postEnd) {
    19         if (inBegin > inEnd) return nullptr;
    20         if (postBegin > postEnd) return nullptr;
    21         
    22         TreeNode *root = new TreeNode(*postEnd);
    23         Iter in_root_pos = find(inBegin, inEnd, *postEnd);
    24         int left_length = in_root_pos - inBegin;
    25         root->left = buildTree(inBegin, in_root_pos - 1, postBegin, postBegin + left_length - 1);
    26         root->right = buildTree(in_root_pos + 1, inEnd, postBegin + left_length, postEnd - 1);
    27         
    28         return root;
    29     }
    30 };
  • 相关阅读:
    图形2d,3d加速简介
    [转]startx启动过程分析
    initrd.img、vmlinux和 vmlinuz
    TSQL建主键索引语句 / 外键
    ASP.NET MVC 2.0在WinXP IIS6下的部署
    update中加入select
    Request
    jqGrid使用总结
    Jquery 表单取值赋值 处理返回json数据
    108个搞笑经典短句(转)
  • 原文地址:https://www.cnblogs.com/vincently/p/4230944.html
Copyright © 2011-2022 走看看