代码随想录day22
235. 二叉搜索树的最近公共祖先
1 class Solution { 2 private: 3 TreeNode* traversal(TreeNode* cur, TreeNode* p, TreeNode* q) { 4 if (cur == NULL) return cur; 5 // 中 6 if (cur->val > p->val && cur->val > q->val) { // 左 7 TreeNode* left = traversal(cur->left, p, q); 8 if (left != NULL) { 9 return left; 10 } 11 } 12 13 if (cur->val < p->val && cur->val < q->val) { // 右 14 TreeNode* right = traversal(cur->right, p, q); 15 if (right != NULL) { 16 return right; 17 } 18 } 19 return cur; 20 } 21 public: 22 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 23 return traversal(root, p, q); 24 } 25 };
701. 二叉搜索树中的插入操作
解题步骤:
1、确定递归函数的参数和返回值;
TreeNode* insertIntoBST(TreeNode* root, int val)
2、确定递归结束的条件;
if(root == nullptr)
{
TreeNode* node = new TreeNode(val);
return root;
}
3、确定单层递归的逻辑
按照二叉搜索树的逻辑遍历树
if (root->val > val) root->left = insertIntoBST(root->left, val);
if (root->val < val) root->right = insertIntoBST(root->right, val);
代码如下:
1 class Solution { 2 public: 3 TreeNode* insertIntoBST(TreeNode* root, int val) { 4 if (root == nullptr) { 5 TreeNode* node = new TreeNode(val); 6 return node; 7 } 8 if (root->val > val) root->left = insertIntoBST(root->left, val); 9 if (root->val < val) root->right = insertIntoBST(root->right, val); 10 return root; 11 } 12 };
解题步骤:
1、确定递归函数的参数和返回值;
TreeNode* deleteNode(TreeNode* root, int key)
2、确定递归的终止条件;
3、确定递归的单层逻辑。
代码如下:
1 class Solution { 2 public: 3 TreeNode* deleteNode(TreeNode* root, int key) { 4 //没找到目标节点 5 //第一种情况:没找到删除的结点,遍历到空结点直接返回 6 if (root == nullptr) return root; 7 //找到目标节点 8 if (root->val == key){ 9 //第二种情况:根节点左右子树都为根节点 10 if (root->left == nullptr && root->right == nullptr){ 11 delete root; 12 return nullptr; 13 } else if (root->left == nullptr) {//第三种情况:左节点为空结点 14 TreeNode* retNode = root->right; 15 delete root; 16 return retNode; 17 } else if (root->right == nullptr) {//第四种情况:右节点为空结点 18 TreeNode* retNode = root->left; 19 delete root; 20 return retNode; 21 } else {//第五种情况:左右子树都不为空 22 TreeNode* cur = root->right;//记录右子树最左边的节点 23 while (cur->left != nullptr) { 24 cur = cur->left; 25 } 26 cur->left = root->left;//把要删除的root的左子树放在cur的左孩子的位置 27 TreeNode* tmp = root;//把要删除的root保存一下 28 root = root->right;// 返回旧root的右孩子作为新root 29 delete tmp; 30 return root; 31 } 32 } 33 if (root->val > key) root->left = deleteNode(root->left, key); 34 if (root->val < key) root->right = deleteNode(root->right, key); 35 return root; 36 } 37 };
浙公网安备 33010602011771号