mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
更新代码块
This commit is contained in:
@@ -77,7 +77,7 @@ if (cur->left == NULL && cur->right == NULL) {
|
||||
|
||||
这里我们先使用vector<int>结构的path容器来记录路径,那么终止处理逻辑如下:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left == NULL && cur->right == NULL) { // 遇到叶子节点
|
||||
string sPath;
|
||||
for (int i = 0; i < path.size() - 1; i++) { // 将path里记录的路径转为string格式
|
||||
@@ -113,7 +113,7 @@ if (cur->right) {
|
||||
|
||||
那么回溯要怎么回溯呢,一些同学会这么写,如下:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left) {
|
||||
traversal(cur->left, path, result);
|
||||
}
|
||||
@@ -129,7 +129,7 @@ path.pop_back();
|
||||
|
||||
那么代码应该这么写:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left) {
|
||||
traversal(cur->left, path, result);
|
||||
path.pop_back(); // 回溯
|
||||
@@ -142,7 +142,7 @@ if (cur->right) {
|
||||
|
||||
那么本题整体代码如下:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
class Solution {
|
||||
private:
|
||||
|
||||
@@ -183,7 +183,7 @@ public:
|
||||
|
||||
那么如上代码可以精简成如下代码:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
class Solution {
|
||||
private:
|
||||
|
||||
@@ -217,20 +217,20 @@ public:
|
||||
|
||||
为了把这份精简代码的回溯过程展现出来,大家可以试一试把:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left) traversal(cur->left, path + "->", result); // 左 回溯就隐藏在这里
|
||||
```
|
||||
|
||||
改成如下代码:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
path += "->";
|
||||
traversal(cur->left, path, result); // 左
|
||||
```
|
||||
|
||||
即:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left) {
|
||||
path += "->";
|
||||
traversal(cur->left, path, result); // 左
|
||||
@@ -245,7 +245,7 @@ if (cur->right) {
|
||||
|
||||
如果想把回溯加上,就要 在上面代码的基础上,加上回溯,就可以AC了。
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
if (cur->left) {
|
||||
path += "->";
|
||||
traversal(cur->left, path, result); // 左
|
||||
@@ -276,7 +276,7 @@ if (cur->right) {
|
||||
|
||||
C++代码如下:
|
||||
|
||||
```C++
|
||||
```CPP
|
||||
class Solution {
|
||||
public:
|
||||
vector<string> binaryTreePaths(TreeNode* root) {
|
||||
|
||||
Reference in New Issue
Block a user