Merge pull request #2400 from Chenxue3/master

Update 0225.用队列实现栈.md 增加C#单队列实现方式
This commit is contained in:
程序员Carl
2024-01-14 16:39:57 +08:00
committed by GitHub
4 changed files with 140 additions and 1 deletions

View File

@ -358,7 +358,84 @@ function connect(root: NodePro | null): NodePro | null {
};
```
```csharp
//递归
public class Solution {
public Node Connect(Node root) {
if (root == null) {
return null;
}
ConnectNodes(root.left, root.right);
return root;
}
private void ConnectNodes(Node node1, Node node2) {
if (node1 == null || node2 == null) {
return;
}
// 将左子节点的 next 指向右子节点
node1.next = node2;
// 递归连接当前节点的左右子节点
ConnectNodes(node1.left, node1.right);
ConnectNodes(node2.left, node2.right);
// 连接跨越父节点的两个子树
ConnectNodes(node1.right, node2.left);
}
}
// 迭代
public class Solution
{
public Node Connect(Node root)
{
Queue<Node> que = new Queue<Node>();
if (root != null)
{
que.Enqueue(root);
}
while (que.Count > 0)
{
var queSize = que.Count;
for (int i = 0; i < queSize; i++)
{
var cur = que.Dequeue();
// 当这个节点不是这一层的最后的节点
if (i != queSize - 1)
{
// 当前节点指向下一个节点
cur.next = que.Peek();
}
// 否则指向空
else
{
cur.next = null;
}
if (cur.left != null)
{
que.Enqueue(cur.left);
}
if (cur.right != null)
{
que.Enqueue(cur.right);
}
}
}
return root;
}
}
```
<p align="center">

View File

@ -1046,6 +1046,8 @@ class MyStack() {
### C#:
> 双队列
```csharp
public class MyStack {
Queue<int> queue1;
@ -1080,6 +1082,54 @@ public class MyStack {
}
```
> 单队列
```c#
/*
* @lc app=leetcode id=225 lang=csharp
* 版本二:单队列
* [225] Implement Stack using Queues
*/
// @lc code=start
public class MyStack {
Queue<int> myQueue;
public MyStack() {
myQueue = new Queue<int>();
}
public void Push(int x) {
myQueue.Enqueue(x);
}
//使用一个队列实现
public int Pop() {
//一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
for (var i = 0; i < myQueue.Count-1; i++)
{
myQueue.Enqueue(myQueue.Dequeue());
}
return myQueue.Dequeue();
}
//复用Pop()的代码
public int Top() {
int res = Pop();
myQueue.Enqueue(res);
return res;
}
public bool Empty() {
return (myQueue.Count == 0);
}
}
// @lc code=end
```
### PHP:
> 双队列
@ -1203,3 +1253,4 @@ impl MyStack {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -302,9 +302,19 @@ impl<T> TreeNode<T> {
}
}
}
```
```
```c#
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -623,3 +623,4 @@ public void Traversal(TreeNode cur, IList<int> res)
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>