@@ -79,15 +79,15 @@ public:
79
79
80
80
代码如下:
81
81
82
- ```
82
+ ```cpp
83
83
TreeNode* trimBST(TreeNode* root, int low, int high)
84
84
```
85
85
86
86
* 确定终止条件
87
87
88
88
修剪的操作并不是在终止条件上进行的,所以就是遇到空节点返回就可以了。
89
89
90
- ```
90
+ ``` cpp
91
91
if (root == nullptr ) return nullptr ;
92
92
```
93
93
@@ -97,7 +97,7 @@ if (root == nullptr ) return nullptr;
97
97
98
98
代码如下:
99
99
100
- ```
100
+ ``` cpp
101
101
if (root->val < low) {
102
102
TreeNode* right = trimBST(root->right, low, high); // 寻找符合区间[low, high]的节点
103
103
return right;
@@ -108,7 +108,7 @@ if (root->val < low) {
108
108
109
109
代码如下:
110
110
111
- ```
111
+ ``` cpp
112
112
if (root->val > high) {
113
113
TreeNode* left = trimBST(root->left, low, high); // 寻找符合区间[low, high]的节点
114
114
return left;
@@ -119,7 +119,7 @@ if (root->val > high) {
119
119
120
120
最后返回root节点,代码如下:
121
121
122
- ```
122
+ ``` cpp
123
123
root->left = trimBST(root->left, low, high); // root->left接入符合条件的左孩子
124
124
root->right = trimBST(root->right, low, high); // root->right接入符合条件的右孩子
125
125
return root;
@@ -133,7 +133,7 @@ return root;
133
133
134
134
如下代码相当于把节点0的右孩子(节点2)返回给上一层,
135
135
136
- ```
136
+ ``` cpp
137
137
if (root->val < low) {
138
138
TreeNode* right = trimBST(root->right, low, high); // 寻找符合区间[low, high]的节点
139
139
return right;
@@ -142,7 +142,7 @@ if (root->val < low) {
142
142
143
143
然后如下代码相当于用节点3的左孩子 把下一层返回的 节点0的右孩子(节点2) 接住。
144
144
145
- ```
145
+ ``` cpp
146
146
root->left = trimBST(root->left, low, high);
147
147
```
148
148
0 commit comments