以下问题,主要是练习递归的使用,体会递归的思想。
Problem 654 最大数二叉树
Medium
C++
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114/*********************************
Given an integer array with no duplicates.
A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed
from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed
from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
Note:
The size of the given array will be in the range [1,1000].
***********************************/
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// method 1 使用迭代器 快了一点
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.empty()) {
return nullptr;
}
auto it = max_element(nums.begin(), nums.end());
TreeNode* root = new TreeNode(*it);
vector<int> left(nums.begin(), it);
vector<int> right(next(it), nums.end());
root->left = constructMaximumBinaryTree(left);
root->right = constructMaximumBinaryTree(right);
return root;
}
// method 2 性能差
TreeNode* construct(vector<int>& nums) {
return build(nums, 0, nums.size());
}
TreeNode* build(vector<int> num, int start, int end) {
if (start == end) {
return nullptr;
}
int maxIndex = findMax(num, start, end);
TreeNode* root = new TreeNode(num[maxIndex]);
root->left = build(num, start, maxIndex);
root->right = build(num, maxIndex + 1, end);
return root;
}
int findMax(vector<int> num, int start, int end) {
int index = start;
int max = num[start];
for (int i = start; i < end; i++) {
if (num[i] > max) {
index = i;
max = num[i];
}
}
return index;
}
};
总结:
1. 使用迭代器速度快了一些
2. 递归循环查找速度显然慢了
3. 非递归版本速度更快,可利用栈实现
以下是 O(n)实现方式(摘自大佬)
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
vector<TreeNode*> stk;
for (int i = 0; i < nums.size(); ++i)
{
TreeNode* cur = new TreeNode(nums[i]);
while (!stk.empty() && stk.back()->val < nums[i])
{
cur->left = stk.back();
stk.pop_back();
}
if (!stk.empty())
stk.back()->right = cur;
stk.push_back(cur);
}
return stk.front();
}
};
递归统计二叉树结点在某区间内的和
1 | /************************************************** |
简单二叉树剪枝
1 | /* |
矩阵递归搜索
1 | /* |
递归的思想和步骤:
- 递归就是找到重复相似的步骤,重复调用同一函数实现。
- 需要找到递归的终结条件。
- 明确多重递归之间的参数变量关系。