剑指offer面试题07. 重建二叉树

/**
 * 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* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return build(preorder,inorder,0,0,inorder.size()-1);
    }
    TreeNode* build(vector<int>& preorder,vector<int>& inorder,int root,int start,int end)
    {
        if(start>end)return NULL;
        TreeNode* tree=new TreeNode(preorder[root]);
        int i=start;
        while(i<end&&preorder[root]!=inorder[i])i++;
        tree->left = build(preorder, inorder, root + 1, start, i - 1);
        tree->right = build(preorder, inorder, root + 1 + i - start, i + 1, end);
        return tree;
    }
};

剑指offer面试题07. 重建二叉树_第1张图片

有点懵,数据结构得看看了!!
看里面的评论写的,树我都不会了

你可能感兴趣的:(算法题)