/
105.从前序与中序遍历序列构造二叉树.cpp
81 lines (76 loc) · 1.97 KB
/
105.从前序与中序遍历序列构造二叉树.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=105 lang=cpp
*
* [105] 从前序与中序遍历序列构造二叉树
*
* https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
*
* algorithms
* Medium (62.87%)
* Likes: 287
* Dislikes: 0
* Total Accepted: 33.3K
* Total Submissions: 53K
* Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]'
*
* 根据一棵树的前序遍历与中序遍历构造二叉树。
*
* 注意:
* 你可以假设树中没有重复的元素。
*
* 例如,给出
*
* 前序遍历 preorder = [3,9,20,15,7]
* 中序遍历 inorder = [9,3,15,20,7]
*
* 返回如下的二叉树:
*
* 3
* / \
* 9 20
* / \
* 15 7
*
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// @lc code=start
/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root = create(0, inorder.size()-1, 0, preorder.size()-1, preorder, inorder);
return root;
}
TreeNode* create(int inL, int inR, int preL, int preR, vector<int>& preorder, vector<int>& inorder) {
if (preL > preR) return nullptr;
int rootVal = preorder[preL];
TreeNode *root = new TreeNode(rootVal);
int k = 0;
for (int i=inL; i<=inR; i++) {
if (rootVal == inorder[i]) {
k = i;
break;
}
}
int numLeft = k- inL; //
root->left = create(inL, k-1, preL+1, preL+numLeft, preorder, inorder);
root->right = create(k+1, inR, preL+numLeft+1, preR, preorder, inorder);
return root;
}
};
// @lc code=end