mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-13 15:56:05 +00:00
build
This commit is contained in:
@@ -196,12 +196,10 @@ comments: true
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
/* 查找节点 */
|
||||
TreeNode? search(int num)
|
||||
{
|
||||
TreeNode? search(int num) {
|
||||
TreeNode? cur = root;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null)
|
||||
{
|
||||
while (cur != null) {
|
||||
// 目标节点在 cur 的右子树中
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// 目标节点在 cur 的左子树中
|
||||
@@ -501,14 +499,12 @@ comments: true
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
/* 插入节点 */
|
||||
void insert(int num)
|
||||
{
|
||||
void insert(int num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root == null) return;
|
||||
TreeNode? cur = root, pre = null;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null)
|
||||
{
|
||||
while (cur != null) {
|
||||
// 找到重复节点,直接返回
|
||||
if (cur.val == num) return;
|
||||
pre = cur;
|
||||
@@ -520,8 +516,7 @@ comments: true
|
||||
|
||||
// 插入节点 val
|
||||
TreeNode node = new TreeNode(num);
|
||||
if (pre != null)
|
||||
{
|
||||
if (pre != null) {
|
||||
if (pre.val < num) pre.right = node;
|
||||
else pre.left = node;
|
||||
}
|
||||
@@ -1004,14 +999,12 @@ comments: true
|
||||
|
||||
```csharp title="binary_search_tree.cs"
|
||||
/* 删除节点 */
|
||||
void remove(int num)
|
||||
{
|
||||
void remove(int num) {
|
||||
// 若树为空,直接提前返回
|
||||
if (root == null) return;
|
||||
TreeNode? cur = root, pre = null;
|
||||
// 循环查找,越过叶节点后跳出
|
||||
while (cur != null)
|
||||
{
|
||||
while (cur != null) {
|
||||
// 找到待删除节点,跳出循环
|
||||
if (cur.val == num) break;
|
||||
pre = cur;
|
||||
@@ -1023,27 +1016,21 @@ comments: true
|
||||
// 若无待删除节点,则直接返回
|
||||
if (cur == null || pre == null) return;
|
||||
// 子节点数量 = 0 or 1
|
||||
if (cur.left == null || cur.right == null)
|
||||
{
|
||||
if (cur.left == null || cur.right == null) {
|
||||
// 当子节点数量 = 0 / 1 时, child = null / 该子节点
|
||||
TreeNode? child = cur.left != null ? cur.left : cur.right;
|
||||
// 删除节点 cur
|
||||
if (pre.left == cur)
|
||||
{
|
||||
if (pre.left == cur) {
|
||||
pre.left = child;
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
pre.right = child;
|
||||
}
|
||||
}
|
||||
// 子节点数量 = 2
|
||||
else
|
||||
{
|
||||
else {
|
||||
// 获取中序遍历中 cur 的下一个节点
|
||||
TreeNode? tmp = cur.right;
|
||||
while (tmp.left != null)
|
||||
{
|
||||
while (tmp.left != null) {
|
||||
tmp = tmp.left;
|
||||
}
|
||||
// 递归删除节点 tmp
|
||||
|
||||
Reference in New Issue
Block a user