二叉树
30. 删除二叉搜索树中的节点
思路:
分类讨论:
一、找不到,返回NULL
二、找到了,讨论结果如下:
- 如果二叉树为空直接返回空
- 左右子节点均空,直接删除
- 左空右不空,直接返回右子节点(上提右子节点)
- 左不空右空,直接返回左子节点(上提左子节点)
- 左不空,且右不空,将左子树接在右子树的最左节点上。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
// 一、没找到
if (root == nullptr) return nullptr;
if (key > root->val) {
root->right = deleteNode(root->right, key);
} else if (key < root->val) {
root->left = deleteNode(root->left, key);
} else { // 二、找到了
if (!root->left && !root->right) { // 1. 左右均空
delete root;
return nullptr;
} else if (!root->left) { // 2. 右不空
TreeNode* tmp = root->right;
delete root;
return tmp;
} else if (!root->right) { // 3. 左不空
TreeNode* tmp = root->left;
delete root;
return tmp;
} else { // 4. 左右均不空
TreeNode* cur = root->right;
while (cur->left) {
cur = cur->left;
}
cur->left = root->left;
TreeNode* tmp = root->right;
delete root;
return tmp;
}
}
return root;
}
};
31. 修剪二叉搜索树
思路1:
递归处理出子树的结果,向上一层返回根节点。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) return root;
if (root->val < low) {
TreeNode* left = trimBST(root->right, low, high);
return left;
} else if (root->val > high) {
TreeNode* right = trimBST(root->left, low, high);
return right;
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
思路2
迭代法:
- 找到第一个出现在区间内的节点作为根节点
- 然后分别处理其左右子树,将树调整成为满足要求的样子
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
// 处理根节点
while (root && (root->val < low || root->val > high)) {
if (root->val < low) root = root->right;
else root = root->left;
}
TreeNode* cur = root;
// 处理左子树
while (cur) {
while (cur->left && cur->left->val < low) cur->left = cur->left->right;
cur = cur->left;
}
cur = root;
// 处理右子树
while (cur) {
while (cur->right && cur->right->val > high) cur->right = cur->right->left;
cur = cur->right;
}
return root;
}
};