代码随想录算法训练营 Day20 二叉搜索树插入 删除 求祖先

二叉树

二叉搜索树

适合中序遍历

题目

235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
利用二叉搜索树性质解题,当夹在 pq 中间的数字时想要的公共祖先
二叉搜索树自带排序,因此二叉搜索树大部分情况都可以使用其自身的排序顺序 (左右)

// 递归
TreeNode* Traversal(TreeNode* cur, TreeNode* p, TreeNode* q) {
	// 终止条件
	if (cur == nullptr) return nullptr;
	// 左
	if (cur->val > p->val && cur->val > q->val) return Traversal(cur->left, p, q);
	// 右
	if (cur->val < p->val && cur->val < q->val) return Traversal(cur->right, p, q);
	return cur;
}

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
	return Traversal(root, p, q);
}

// 迭代
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
	std::stack<TreeNode*> st;
	if (root != nullptr) st.push(root);
	while (!st.empty()) {
		TreeNode* cur = st.top();
		st.pop();

		if (cur->val > p->val && cur->val > q->val) st.push(cur->left);
		else if (cur->val < p->val && cur->val < q->val) st.push(cur->right);
		else return cur;
	}
	return root;
}

701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
插入新节点都是在叶子节点处

// 递归1
TreeNode* insertIntoBST(TreeNode* root, int val) {
	// 终止条件 在叶子节点插入
	if (root == nullptr) {
		TreeNode* cur = new TreeNode(val);
		return cur;
	}
	// 左
	if (root->val > val) root->left = insertIntoBST(root->left, val);
	// 右
	if (root->val < val) root->right = insertIntoBST(root->right, val);
	return root;
}

// 递归2
TreeNode* parent;
void traversal(TreeNode* cur, int val) {
	if (cur == NULL) {
		TreeNode* node = new TreeNode(val);
		if (val > parent->val) parent->right = node;
		else parent->left = node;
		return;
	}
	parent = cur;
	if (cur->val > val) traversal(cur->left, val);
	if (cur->val < val) traversal(cur->right, val);
	return;
}

TreeNode* insertIntoBST(TreeNode* root, int val) {
	parent = new TreeNode(0);
	if (root == NULL) {
		root = new TreeNode(val);
	}
	traversal(root, val);
	return root;
}

450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
分五种删除情况,找不到、左右为空、左空、右空、均不空
每种情况返回结点指针即可,最后一种情况需要额外添加寻找当前节点右子树最左边的叶子节点嫁接

TreeNode* deleteNode(TreeNode* root, int key) {
	// 终止条件 五种情况
	// 1 找不到
	if (root == nullptr) return nullptr;
	if (root->val == key) {
		// 2 均空
		if (root->left == nullptr && root->right == nullptr) {
			delete root;
			return nullptr;
		}
		// 3 左空
		else if (root->left == nullptr) {
			TreeNode* cur = root->right;
			delete root;
			return cur;
		}
		// 4 右空
		else if (root->right == nullptr) {
			TreeNode* cur = root->left;
			delete root;
			return cur;
		}
		// 5 均不空
		else {
			// 右节点继承
			TreeNode* cur = root->right;
			while (cur->left!=nullptr) cur = cur->left;
			cur->left = root->left;
			TreeNode* res = root->right;
			delete root;
			return res;
		}
	}

	// 左
	if (root->val < key) root->right = deleteNode(root->right, key);
	// 右
	if (root->val > key) root->left = deleteNode(root->left, key);
	return root;
}

你可能感兴趣的:(算法)