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 };
  • 相关阅读:
    java读取excel文件内容
    JavaScript函数写法整理
    Redis命令
    Redis简单入门
    Redis介绍
    NodeJS代码调试
    React组件生命周期
    解决swiper动态改变数据后分页混乱问题
    [LeetCode] 343. Integer Break
    [LeetCode] 304. Range Sum Query 2D
  • 原文地址:https://www.cnblogs.com/vincently/p/4230944.html
Copyright © 2011-2022 走看看