其他分享
首页 > 其他分享> > 剑指 Offer 07. 重建二叉树

剑指 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;


    }
};

 

标签:preorder,TreeNode,07,val,Offer,int,inorder,二叉树,root
来源: https://www.cnblogs.com/WTSRUVF/p/15825274.html