Middle-题目68:106. Construct Binary Tree from Inorder and Postorder Traversal

题目原文:
Given inorder and postorder traversal of a tree, construct the binary tree.
题目大意:
给出一棵二叉树中序和后序遍历的序列,构建这个二叉树。
题目分析:
中序遍历的顺序是左-中-右,而后序遍历是左-右-中,所以取后序遍历的最后一个元素到中序遍历串中匹配,匹配到之后递归根据子树的中序和后序序列构建左右子树。
源码:(language:c)

struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
    if(inorderSize == 0 && postorderSize == 0)
        return NULL;
    else {
        int middle = postorder[postorderSize-1];
        int i;
        for (i = 0;inorder[i] != middle; i++);
        struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); //generate root
        root->val = middle;
        root->left = buildTree(inorder, i, postorder, i);
        root->right = buildTree(&inorder[i+1], inorderSize-i-1, &postorder[i], inorderSize-i-1);
        return root;
    }
}

成绩:
20ms,35.14%,众数20ms,43.24%
Cmershen的碎碎念:
本题的Java入口参数是(int[],int[]),而C中使用的是指针,这样可以有效的截取子数组。所以指针虽然很容易引发各种缺陷,是危险的,但有时也提供了很大的方便。

你可能感兴趣的:(Middle-题目68:106. Construct Binary Tree from Inorder and Postorder Traversal)