Leetcode 105 Construct Binary Tree from Preorder and Inorder Traversal
給出二叉樹的先根遍歷和中根遍歷,構造二叉樹。
瞭解先根遍歷和中根遍歷的特點。每次在先根遍歷陣列中最左邊的就是二叉樹的根,然後去中根遍歷陣列中找到根,根左邊的就是左子樹,對於左子樹和右子樹採取同樣的求法:去先根遍歷陣列中找根,利用中根遍歷陣列劃分左右子樹,遞迴求解。
class Solution {
public:
TreeNode* help(vector<int>& preorder,int l1, int r1, vector<int>& inorder, int l2, int r2)
{
if(l1>r1)
return nullptr;
else
{
int i;
TreeNode* root=new TreeNode(preorder[l1]);
for(i=l2; i<=r2; ++i)
{
if(inorder[i]==preorder[l1])
break;
}
root->left=help(preorder, l1+1, i+l1-l2, inorder, l2, i-1);
root->right=help(preorder, i+l1-l2+1, r1, inorder, i+1, r2);
return root;
}
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return help(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
};
相關文章
- [leetcode]binary-tree-inorder-traversalLeetCode
- LeetCode | 144. Binary Tree Preorder TraversalLeetCode
- Leetcode 144. Binary Tree Preorder TraversalLeetCode
- Leetcode 94. Binary Tree Inorder TraversalLeetCode
- LeetCode之Construct String from Binary Tree(Kotlin)LeetCodeStructKotlin
- Construct String from Binary TreeStruct
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode | 145. Binary Tree Postorder TraversalLeetCode
- Leetcode 145. Binary Tree Postorder TraversalLeetCode
- LeetCode 272 Closest Binary Tree Traversal II 解題思路LeetCode
- [LeetCode] 2196. Create Binary Tree From DescriptionsLeetCode
- Binary-tree-level-order-traversal
- 102-Binary Tree Level Order Traversal
- 107-Binary Tree Level Order Traversal II
- 103. Binary Tree Zigzag Level Order Traversal
- Leetcode Binary Tree PathsLeetCode
- [LeetCode] Construct Quad Tree 建立四叉樹LeetCodeStruct
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode 543. Diameter of Binary TreeLeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- LeetCode のminimum-depth-of-binary-treeLeetCode
- Leetcode 298 Binary Tree Longest Consecutive SequenceLeetCode
- LeetCode 104. Maximum Depth of Binary TreeLeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode
- leetcode-124-Binary Tree Maximum Path SumLeetCode
- [LeetCode] 501. Find Mode in Binary Search TreeLeetCode
- [LeetCode] 671. Second Minimum Node In a Binary TreeLeetCode
- LeetCode 124. Binary Tree Maximum Path SumLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- LeetCode 501. Find Mode in Binary Search TreeLeetCode
- LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難LeetCodeC++
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode