Skip to content

Commit bce2ddd

Browse files
author
zhangrui
committed
450. 删除二叉搜索树中的节点
1 parent 7593bff commit bce2ddd

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

deleteNode/deleteNode.h

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//
2+
// Created by Administrator on 2021/8/27.
3+
//
4+
5+
#ifndef ALGORITHM_DELETENODE_H
6+
#define ALGORITHM_DELETENODE_H
7+
8+
/**
9+
* 450. 删除二叉搜索树中的节点
10+
* 给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
11+
* 一般来说,删除节点可分为两个步骤: 首先找到需要删除的节点; 如果找到了,删除它。
12+
* 说明: 要求算法时间复杂度为 O(h),h 为树的高度。
13+
*
14+
* 求解策略:
15+
* 利用二分查找策略找到所需要删除的节点 p.
16+
* 若不存在子节点, 直接删除p;
17+
* 若p只存在一个子节点x时, 用x替换p即可.
18+
* 若p只存在一个子节点x时,则找到p的中序遍历序列的直接后继元素x. 交换p与x, 删除x;
19+
*/
20+
21+
#include <algorithm>
22+
#include "../common.h"
23+
24+
using namespace std;
25+
26+
TreeNode *deleteNode(TreeNode *root, int key) {
27+
if (!root) return nullptr;
28+
if (root->val == key) {
29+
if (!root->right) {
30+
TreeNode *tmp = root;
31+
root = root->left;
32+
delete tmp;
33+
return root;
34+
}
35+
if (!root->left) {
36+
TreeNode *tmp = root;
37+
root = root->right;
38+
delete tmp;
39+
return root;
40+
} else {
41+
TreeNode *nex = root->right;
42+
while (nex->left)nex = nex->left;
43+
nex->left = root->left;
44+
TreeNode *tmp = root;
45+
root = root->right;
46+
delete tmp;
47+
return root;
48+
}
49+
}
50+
if (key < root->val) root->left = deleteNode(root->left, key);
51+
if (key > root->val) root->right = deleteNode(root->right, key);
52+
return root;
53+
}
54+
55+
#endif //ALGORITHM_DELETENODE_H

0 commit comments

Comments
 (0)