Skip to content

Commit 3d041ae

Browse files
committed
Add Solution 105[CPP]
1 parent d6fa0da commit 3d041ae

File tree

2 files changed

+95
-0
lines changed

2 files changed

+95
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
## 从前序与中序遍历序列构造二叉树
2+
3+
### 问题描述
4+
根据一棵树的前序遍历与中序遍历构造二叉树。
5+
6+
注意:
7+
你可以假设树中没有重复的元素。
8+
9+
例如,给出
10+
```
11+
前序遍历 preorder = [3,9,20,15,7]
12+
中序遍历 inorder = [9,3,15,20,7]
13+
```
14+
15+
返回如下的二叉树:
16+
```
17+
3
18+
/ \
19+
9 20
20+
/ \
21+
15 7
22+
```
23+
---------------
24+
25+
### 思路
26+
27+
利用树的前序遍历和中序遍历特性+递归实现
28+
29+
对树进行前序遍历,每一个元素,在树的中序遍历中找到概元素;在中序遍历中,该元素的左边是它的左子树的全部元素,右边是它的右子树的全部元素,以此为递归条件,确定左右子树的范围
30+
31+
```CPP
32+
/**
33+
* Definition for a binary tree node.
34+
* struct TreeNode {
35+
* int val;
36+
* TreeNode *left;
37+
* TreeNode *right;
38+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
39+
* };
40+
*/
41+
class Solution {
42+
public:
43+
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
44+
int pRight = preorder.size()-1;
45+
int iRight = inorder.size()-1;
46+
return build(preorder,inorder,0,pRight,0,iRight);
47+
}
48+
49+
50+
TreeNode* build(vector<int>& preorder,vector<int>& inorder,int pLeft,int pRight,int iLeft,int iRight){
51+
if(pLeft > pRight)return NULL;
52+
53+
TreeNode *node = new TreeNode(preorder[pLeft]);
54+
int idx = iLeft;
55+
56+
while(inorder[idx] != preorder[pLeft])idx++;
57+
node->left = build(preorder,inorder,pLeft+1,pLeft+idx-iLeft,iLeft,idx-1);
58+
node->right = build(preorder,inorder,pLeft+idx-iLeft+1,pRight,idx+1,iRight);
59+
return node;
60+
}
61+
};
62+
63+
```
64+
65+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
13+
int pRight = preorder.size()-1;
14+
int iRight = inorder.size()-1;
15+
return build(preorder,inorder,0,pRight,0,iRight);
16+
}
17+
18+
19+
TreeNode* build(vector<int>& preorder,vector<int>& inorder,int pLeft,int pRight,int iLeft,int iRight){
20+
if(pLeft > pRight)return NULL;
21+
22+
TreeNode *node = new TreeNode(preorder[pLeft]);
23+
int idx = iLeft;
24+
25+
while(inorder[idx] != preorder[pLeft])idx++;
26+
node->left = build(preorder,inorder,pLeft+1,pLeft+idx-iLeft,iLeft,idx-1);
27+
node->right = build(preorder,inorder,pLeft+idx-iLeft+1,pRight,idx+1,iRight);
28+
return node;
29+
}
30+
};

0 commit comments

Comments
 (0)