Middle-题目71:105. Construct Binary Tree from Preorder and Inorder Traversal

原创 2016年05月31日 16:41:28

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

struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    if(preorderSize == 0 && inorderSize == 0)
        return NULL;
    else {
        int middle = preorder[0];
        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(preorder+1, i, inorder, i);
        root->right = buildTree(preorder+i+1, preorderSize-i-1, inorder+i+1, inorderSize-i-1);
        return root;
    }    
}

成绩:
20ms,beats 23.68%,众数20ms,36.84%
Cmershen的碎碎念:
要注意,前序和后序遍历是不能唯一确定二叉树的。但是前序(中序,后序)+层次遍历能否确定二叉树,如何还原二叉树,还有待考虑。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

Construct Binary Tree from Preorder and Inorder Traversal LeetCode 105

题目描述: Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may as...
  • bu_min
  • bu_min
  • 2015年05月27日 10:22
  • 256

105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume th...
  • x_shuck
  • x_shuck
  • 2016年01月10日 22:14
  • 216

105. Construct Binary Tree from Preorder and Inorder Traversal,前序+中序 构建 树

观察:             A          /      \        B      C       /   \    D    E preorder: A B D E C ...

leetcode 105-106:Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume th...

LeetCode: Construct Binary Tree from Preorder and Inorder Traversal [105]

【题目】 Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assu...

剑指offer 面试题6:重建二叉树(Leetcode105. Construct Binary Tree from Preorder and Inorder Traversal) 解题报告

剑指offer 重建二叉树 参与人数:5246  时间限制:1秒  空间限制:32768K 题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍...

【LeetCode】105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51471280Subject 出处:https://leetcode.com/pro...

<LeetCode OJ> 105. Construct Binary Tree from Preorder and Inorder Traversal

Total Accepted: 65143 Total Submissions: 224882 Difficulty: Medium Given preorder and inorder t...

【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】

【106-Construct Binary Tree from Preorder and Inorder Traversal(通过前序和中序遍历构造二叉树)】【LeetCode-面试算法经典-Java...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目71:105. Construct Binary Tree from Preorder and Inorder Traversal
举报原因:
原因补充:

(最多只允许输入30个字)