leetcode 105 —— Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:工具书阅读软件 编辑:程序博客网 时间:2024/06/07 05:34
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:在中序中搜索先序的第一个节点,就能将左子树,根,右子树全部明确。搜索改为二分法,反而降低了效率。后续继续改进
class Solution {public:TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {int n = preorder.size() - 1;return createTree(preorder, 0, n, inorder, 0, n );}TreeNode* createTree(vector<int>& preorder,int start1,int end1, vector<int>& inorder,int start2,int end2) {//if (start1<0||end1>=preorder.size()||start2<0||end2>=preorder.size()||start1 > end1||start2>end2)if (start1 > end1)return nullptr;TreeNode* root = new TreeNode(preorder[start1]);int i = 0;while (start2+i <= end2 &&inorder[start2+i] != preorder[start1] )i++;root->left = createTree(preorder, start1 + 1, start1+i, inorder, start2, start2+i - 1);root->right = createTree(preorder,start1+ i + 1, end1, inorder,start2+ i + 1, end2);return root;}};
0 0
- LeetCode(105)Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal [105]
- 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
- Construct Binary Tree from Preorder and Inorder Traversal LeetCode 105
- 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
- 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
- java多文本框使用右键弹出菜单复制粘贴剪切功能实现
- 【Android UI】ViewPage
- 深入理解Aop编程思想
- Cocos2d-x学习笔记(五)—— 常见UI界面(未完全)
- C++面向对象高级开发No.1 - Class Without Pointer
- leetcode 105 —— Construct Binary Tree from Preorder and Inorder Traversal
- BestCoder Round #50 (div.2) 1003
- java特殊对象及其应用2(时间计算)
- HDU 4940 Destroy Transportation system(上下界网络流)
- C++面向对象高级开发No.2 - Class With Pointer
- poj 2481 Cows 树状数组
- 【笔试】7、统计出其中英文字母、空格、数字和其它字符的个数
- 黑马程序员--java基础--基础语法
- makefile 多目标和多规则