NO.105 previous order and a binary tree configuration sequence preorder

Traversing the binary tree is configured in accordance with the sequence preorder traversal of a tree.

Note:
You can assume that the tree does not duplicate elements.

For example, given

Preorder traversal preorder = [3,9,20,15,7]
preorder inorder = [9,3,15,20,7]

Returns the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
    if(preorderSize==0||preorderSize!=inorderSize)return NULL;
    struct TreeNode* ret=(struct TreeNode *)malloc(sizeof(struct TreeNode));
    int left_len=0;
    ret->val=preorder[0];
    for(int i=0;i<inorderSize;i++)
    {
        if(inorder[i]==preorder[0])break;
        left_len++;
    }
    assert(left_len<preorderSize);
    ret->left=buildTree(preorder+1,left_len,inorder,left_len);
    ret->right=buildTree(preorder+1+left_len,preorderSize-1-left_len,inorder+1+left_len,preorderSize-1-left_len);
    return ret;
}

When execution: 24 ms, beat the 93.00% of all users in C submission

Memory consumption: 12.9 MB, defeated 100.00% of all users in C submission

Guess you like

Origin blog.csdn.net/xuyuanwang19931014/article/details/91412053