目录
一、(leetcode 235)二叉搜索树的最近公共祖先
二、(leetcode 701)二叉搜索树中的插入操作
三、(leetcode 450)删除二叉搜索树中的节点
一、(leetcode 235)二叉搜索树的最近公共祖先
力扣题目链接
状态:没有思路,还是236的套路。
利用二叉搜索树的特性进行分析,不需要对中间节点进行操作,所以没办法区分前/中/后序遍历。
class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(root->val > p->val && root->val > q->val){return lowestCommonAncestor(root->left, p, q);}else if(root->val < p->val && root->val < q->val){return lowestCommonAncestor(root->right, p, q);}else return root;}
};
二、(leetcode 701)二叉搜索树中的插入操作
力扣题目链接
class Solution {
public:TreeNode* insertIntoBST(TreeNode* root, int val) {if(root == nullptr){TreeNode* node = new TreeNode(val);return node;}if(root->val > val) root->left = insertIntoBST(root->left, val);if(root->val < val) root->right = insertIntoBST(root->right, val);return root;}
};
三、(leetcode 450)删除二叉搜索树中的节点
力扣题目链接
状态:比上一题复杂得多
介绍一个二叉树的通用方法
class Solution {
public:TreeNode* deleteNode(TreeNode* root, int key) {// 二叉树通用法if(root == nullptr) return root;if(root->val == key){if(root->right == nullptr){return root->left;}TreeNode* cur = root->right;while(cur->left){cur = cur->left;}swap(root->val, cur->val);}root->left = deleteNode(root->left, key);root->right = deleteNode(root->right, key);return root;}
};