剑指 Offer 07. 重建二叉树

力扣中不要用static

/**
 * 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:
    int i = 0;
    void build(vector<int>& preorder, vector<int>& inorder, TreeNode* &root, int x, int y)
    {

        if(x > y)
        {
            root = NULL;
            return;
        }
        root = (TreeNode*) malloc(sizeof(TreeNode));
        root->val = preorder[i++];
        int j;
        for(j = x; j <= y && inorder[j] != root->val; j++);
        build(preorder, inorder, root->left, x, j - 1);
        build(preorder, inorder, root->right, j + 1, y);
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        TreeNode* root;
        build(preorder, inorder, root, 0, inorder.size() - 1);
        return root;


    }
};

 

上一篇:LeetCode-106-从中序与后序遍历序列构造二叉树


下一篇:一位设计师对未来的指导