Skip to content

Commit

Permalink
update 0116.填充每个节点的下一个右侧节点指针.md 增加C#迭代和递归实现
Browse files Browse the repository at this point in the history
  • Loading branch information
XueshanChen committed Jan 11, 2024
1 parent 650e33b commit b134870
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
77 changes: 77 additions & 0 deletions problems/0116.填充每个节点的下一个右侧节点指针.md
Original file line number Diff line number Diff line change
Expand Up @@ -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">
Expand Down
1 change: 1 addition & 0 deletions problems/二叉树的递归遍历.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>

0 comments on commit b134870

Please sign in to comment.