• 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 };
  • 相关阅读:
    Java day 15
    Java day 14
    Java day 13
    Java day 12
    Java day 11
    Java day 10
    Java day 9
    Java day 8
    Java day 7
    Java day 6
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3675864.html
Copyright © 2020-2023  润新知