构建二叉树-分治策略

 前中后序构建二叉树

class Solution {
public:
    TreeNode* buildTree(vector& preorder,vector&inorder) { 
        return Helper(preorder, 0, preorder.size() - 1, inorder, 0,
                      inorder.size() - 1);
    }
    TreeNode* Helper(vector& preorder, int preStart, int preEnd,
                     vector& inorder, int inStart, int inEnd) {
        if (preStart > preEnd)
            return NULL;
        TreeNode* root = new TreeNode(preorder[preStart]);
        int index = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == root->val) {
                index = i;
                break;
            }
        }
        root->left =
            Helper(preorder, preStart + 1, preStart + (index - inStart),
                   inorder, inStart, index - 1);
        root->right = Helper(preorder, preStart + (index - inStart) + 1, preEnd,
                             inorder, index + 1, inEnd);
        return root;
    }
};

你可能感兴趣的:(#力扣牛客刷题,算法,leetcode,数据结构)