mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -87,7 +87,7 @@ public:
|
|||||||
|
|
||||||
本题使用层序遍历是最为直观的,如果对层序遍历不了解,看这篇:[二叉树:层序遍历登场!](https://programmercarl.com/0102.二叉树的层序遍历.html)。
|
本题使用层序遍历是最为直观的,如果对层序遍历不了解,看这篇:[二叉树:层序遍历登场!](https://programmercarl.com/0102.二叉树的层序遍历.html)。
|
||||||
|
|
||||||
层序遍历本来就是一层一层的去遍历,记录一层的头结点(nodePre),然后让nodePre指向当前遍历的节点就可以了。
|
遍历每一行的时候,如果不是最后一个Node,则指向下一个Node;如果是最后一个Node,则指向nullptr。
|
||||||
|
|
||||||
代码如下:
|
代码如下:
|
||||||
|
|
||||||
@ -96,27 +96,18 @@ class Solution {
|
|||||||
public:
|
public:
|
||||||
Node* connect(Node* root) {
|
Node* connect(Node* root) {
|
||||||
queue<Node*> que;
|
queue<Node*> que;
|
||||||
if (root != NULL) que.push(root);
|
if (root != nullptr) que.push(root);
|
||||||
while (!que.empty()) {
|
while (!que.empty()) {
|
||||||
int size = que.size();
|
int size = que.size();
|
||||||
vector<int> vec;
|
for (int i = 0; i < size; ++i) {
|
||||||
Node* nodePre;
|
Node* node = que.front();
|
||||||
Node* node;
|
|
||||||
for (int i = 0; i < size; i++) { // 开始每一层的遍历
|
|
||||||
if (i == 0) {
|
|
||||||
nodePre = que.front(); // 记录一层的头结点
|
|
||||||
que.pop();
|
que.pop();
|
||||||
node = nodePre;
|
if (i != size - 1) {
|
||||||
} else {
|
node->next = que.front(); //如果不是最后一个Node 则指向下一个Node
|
||||||
node = que.front();
|
} else node->next = nullptr; //如果是最后一个Node 则指向nullptr
|
||||||
que.pop();
|
if (node->left != nullptr) que.push(node->left);
|
||||||
nodePre->next = node; // 本层前一个节点next指向本节点
|
if (node->right != nullptr) que.push(node->right);
|
||||||
nodePre = nodePre->next;
|
|
||||||
}
|
}
|
||||||
if (node->left) que.push(node->left);
|
|
||||||
if (node->right) que.push(node->right);
|
|
||||||
}
|
|
||||||
nodePre->next = NULL; // 本层最后一个节点指向NULL
|
|
||||||
}
|
}
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
|
@ -69,7 +69,7 @@
|
|||||||
|
|
||||||
相信动规的题目,很大部分同学都是这样做的。
|
相信动规的题目,很大部分同学都是这样做的。
|
||||||
|
|
||||||
看一下题解,感觉看懂了,然后照葫芦画瓢,如果能正好画对了,万事大吉,一旦要是没通过,就怎么改都通过不了,对 dp数组的初始化,递归公式,遍历顺序,处于一种黑盒的理解状态。
|
看一下题解,感觉看懂了,然后照葫芦画瓢,如果能正好画对了,万事大吉,一旦要是没通过,就怎么改都通过不了,对 dp数组的初始化,递推公式,遍历顺序,处于一种黑盒的理解状态。
|
||||||
|
|
||||||
写动规题目,代码出问题很正常!
|
写动规题目,代码出问题很正常!
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user