Middle-题目71:105. Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:数据库架构 编辑:程序博客网 时间:2024/05/22 08:26
题目原文:
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的碎碎念:
要注意,前序和后序遍历是不能唯一确定二叉树的。但是前序(中序,后序)+层次遍历能否确定二叉树,如何还原二叉树,还有待考虑。
0 0
- Middle-题目71:105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode --- 105. Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]*105.Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] 105.Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal LeetCode
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode#105. Construct Binary Tree from Preorder and Inorder Traversal
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
- Middle-题目70:103. Binary Tree Zigzag Level Order Traversal
- Cisco 交换机端口限速
- 【转】属性与字段的区别
- leetcode zigzag代码
- 循环代替递归
- Middle-题目71:105. Construct Binary Tree from Preorder and Inorder Traversal
- OpenCV下实现单窗口显示多幅图像的源码!
- Android开发之内存优化探讨(2)空间复杂度与时间复杂度以及实际场景的选择
- JVm性能调优4:GC日志分析
- 证书证书
- 区分JS中的undefined,null,"",0和false
- fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- 一文看懂大数据的技术生态圈,Hadoop,hive,spark都有了
- java.lang.IllegalStateException: TimerTask is scheduled already问题分析