zoukankan      html  css  js  c++  java
  • [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal

    Given preorder and inorder 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     template<typename Iter>
    13     TreeNode *buildTree(Iter preBegin, Iter preEnd, Iter inBegin, Iter inEnd) {
    14         if (preBegin > preEnd) return nullptr;
    15         if (inBegin > inEnd) return nullptr;
    16         
    17         int root_val = *preBegin;
    18         TreeNode *root = new TreeNode(root_val);
    19         Iter in_root_pos = find(inBegin, inEnd, root_val);
    20         int left_size = in_root_pos - inBegin;
    21         root->left = buildTree(preBegin + 1, preBegin + left_size, inBegin, in_root_pos - 1);
    22         root->right = buildTree(preBegin + left_size + 1, preEnd, in_root_pos + 1, inEnd);
    23         
    24         return root;
    25     }
    26     
    27     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    28         if (preorder.empty() || inorder.empty())
    29             return NULL;
    30             
    31         return buildTree(preorder.begin(), preorder.end() - 1, inorder.begin(), inorder.end() - 1);
    32     }
    33 };
  • 相关阅读:
    容器技术问题
    URL和URL
    容器和注入技术
    云计算应用开发与实践读书 笔记(三)
    云计算应用开发与实践读书 笔记 (二 )
    云计算应用开发与实践读书 笔记
    C++学习之DLL注入
    c语言学习,模拟栈操作
    领悟百分比定位
    强大的第三方工具autoPrefixer
  • 原文地址:https://www.cnblogs.com/vincently/p/4230526.html
Copyright © 2011-2022 走看看