`

LeetCode 105 - 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.

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    int *pre = &preorder[0];
    int *in = &inorder[0];
    return build(pre, in, inorder.size());
}

TreeNode *build(int *pre, int *in, int n) {
    if(n == 0) return nullptr;
    TreeNode *root = new TreeNode(pre[0]);
    int i = 0;
    for(; i<n; i++) {
        if(in[i] == pre[0]) break;
    }
    root->left = build(pre+1, in, i);
    root->right = build(pre+i+1, in+i+1, n-i-1);
    return root;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics