- LeetCode #105 #106 2018-08-12
- [Leetcode]105. Construct Binary
- Leetcode - Binary Tree 二叉树 [持续更新
- [LeetCode] 105. Construct Binary
- [leetcode] 105. Construct Binary
- Leetcode 105. Construct Binary T
- 2019-06.23-2019.06.30
- LeetCode | 0105. Construct Binar
- Construct Binary Tree from Preor
- 2.Construct Binary Tree from Pre
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 that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
题意:中序加前序构建二叉树
思路,从前序中找到在根结点在中序中的位置,然后找出左右子树,递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int,int>pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=preorder.size();
for(int i=0;i<n;i++)pos[inorder[i]]=i;
return dfs(preorder,inorder,0,n-1,0,n-1);
}
TreeNode* dfs(vector<int>& preorder, vector<int>& inorder,int pl,int pr,int il,int ir) {
if(pl>pr)
return NULL;
int val=preorder[pl];
int k=pos[val];
int len=k-il;
auto root=new TreeNode(val);
root->left=dfs(preorder,inorder,pl+1,pl+len,il,k-1);
root->right=dfs(preorder,inorder,pl+len+1,pr,k+1,ir);
return root;
}
};







网友评论