二叉搜索树中的插入,删除,修剪
2026/7/24 23:32:51 网站建设 项目流程

插入:

这个递归逻辑一开始我自己写的时候没想出来,一看题解竟然这么简单。可以记一下,或者先试着自己写一下看行不行。

DeepSeek

  • 最底层(遇到 NULL):返回新创建的节点指针

  • 中间层(非 NULL 的节点):执行root->left = 递归调用root->right = 递归调用把底层返回的新节点挂到自己身上。然后返回自己(root给上一层。

  • 最顶层(根节点):返回整棵树的根节点指针给主调函数

lass Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if(root==NULL){ TreeNode*node=new TreeNode(val); return node; } if(val<root->val)root->left=insertIntoBST(root->left,val); if(val>root->val)root->right=insertIntoBST(root->right,val); return root; } };

删除:

DeepSeek

这个逻辑很简单,但是不要忘了判断key=root val,否则每个节点都可以进入流程,根节点无论是不是要删除的都会被删除了,题目不难,应该自己再写一遍。

/** * 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==NULL)return NULL; else if(root->val==key){ if(!root->left&&!root->right)return NULL; else if(root->left&&!root->right)return root->left; else if(!root->left&&root->right)return root->right; else if(root->left&&root->right){ TreeNode* cur=nullptr; cur=root->right; while(cur->left){ cur=cur->left; } TreeNode* pre=root->left; cur->left=pre; TreeNode *tmp=root; root=root->right; delete tmp; return root; }} if(key>root->val)root->right=deleteNode(root->right,key); if(key<root->val)root->left=deleteNode(root->left,key); return root; } };

修改:

class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(root==nullptr)return root; if(root->val<low){ TreeNode*cur=trimBST(root->right,low,high); return cur; } if(root->val>high){ TreeNode*cur=trimBST(root->left,low,high); return cur; } root->left=trimBST(root->left,low,high); root->right=trimBST(root->right,low,high); return root; } };

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询