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

    Solution: Recursion.

     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> &preorder, vector<int> &inorder) {
    13         return buildTreeRe(preorder.begin(), inorder.begin(), preorder.size());
    14     }
    15     
    16     TreeNode* buildTreeRe(vector<int>::iterator preorder, vector<int>::iterator inorder, int N) 
    17     {
    18         if(N <= 0) return NULL;
    19         vector<int>::iterator it = find(inorder, inorder + N, *preorder);
    20         int pos = it - inorder;
    21         TreeNode* root = new TreeNode(*preorder);
    22         root->left = buildTreeRe(preorder+1, inorder, pos);
    23         root->right = buildTreeRe(preorder+pos+1, inorder+pos+1, N-1-pos);
    24         return root;
    25     }
    26 };
  • 相关阅读:
    NOIP2018游记-DAY1
    NOIP2018游记-DAY0
    18.11.7绍一模拟赛
    [SPOJ]SELTEAM
    18.11.5绍一模拟赛
    18.11.2绍一模拟赛
    [模拟赛]世界杯
    [模拟赛]路途
    乘法逆元的研究
    子查询,TOP_N,分页,行转列
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3675864.html
Copyright © 2011-2022 走看看