LeetCode105 Construct Binary Tree from Preorder and Inorder Traversal

题目链接:

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

题目描述:

前序中序建树。

题目分析:

就是先建立好根节点,再根据这个根节点递归的不停的划分左右子树。

代码:

void createBinaryTree(struct TreeNode* *root, int* preorder, int* inorder, int len){
    for (int i = 0; i<len; i++){
        if (preorder[0] == inorder[i]){
            *root = (struct TreeNode*)malloc(sizeof(struct TreeNode*));
            (*root)->val = preorder[0];
            (*root)->left = (*root)->right = NULL;
            createBinaryTree(&((*root)->left), preorder + 1, inorder, i); createBinaryTree(&((*root)->right), preorder + i + 1, inorder+i+1, len - i - 1); break; } } } struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { struct TreeNode* root = NULL; createBinaryTree(&root, preorder, inorder, inorderSize); return root; }

你可能感兴趣的:(LeetCode,递归,树,序列建树)