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.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

思路还是比较简单的,在中序遍历中找前序遍历的值,然后递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* dfs(vector<int>& preorder, vector<int>& inorder, int l, int r, int &num) {
        TreeNode* root = new TreeNode(preorder[num]);
        if (l > r) return nullptr;
        int p = l;
        while (p <= r && inorder[p] != preorder[num]) ++p;
        ++num;
        root->left = dfs(preorder, inorder, l, p-1, num);
        root->right = dfs(preorder, inorder, p+1, r, num);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int r = inorder.size() - 1;
        if (r == -1) return nullptr;
        int l = 0, num = 0;
        return dfs(preorder, inorder, l, r, num);
    }
};
posted on 2018-03-26 22:04  Beserious  阅读(103)  评论(0编辑  收藏  举报