leetcode-剑指07-OK

// language c
// 剑指07
// https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/


/**
 * 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)
        return NULL;
    int rootval = preorder[0];
    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val = rootval;
    int leftsize = 0;
    while(inorder[leftsize] !=rootval)
        leftsize++;
    root->left = buildTree(preorder+1, leftsize, inorder,leftsize);
    int rightsize = preorderSize -1 - leftsize;
    root->right = buildTree(preorder+leftsize+1, rightsize, inorder+leftsize+1,rightsize);
    return root;
}
posted @ 2021-01-27 13:22  RougeBW  阅读(21)  评论(0编辑  收藏  举报