LeetCode 从前序和中序遍历序列构造二叉树 C语言

  • 思路
    写数据结构试卷的时候天天画那些二叉树的啦,思路很明显嘛,前序序列即根序列,遍历中序序列找到根结点,则左边是左子树,右边是右子树,但是条件不太好判断,应该要能够更加熟地练掌握
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    if(preorderSize==0)
        return NULL;
	struct TreeNode* root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
    root->val = preorder[0];
    int n=0;
    for(; inorder[n]!=preorder[0]; n++);
    if(n==0)
        root->left = NULL;
    else
        root->left = buildTree(preorder+1, n, inorder, n);
    if(inorderSize-1==0)
        root->right = NULL;
    else
        root->right = buildTree(preorder+n+1, preorderSize-n-1, inorder+n+1, inorderSize-n-1);
    return root;
}

你可能感兴趣的:(LeetCode 从前序和中序遍历序列构造二叉树 C语言)