二叉搜索树中的插入,删除,修剪

发布时间:2026/7/24 23:32:57
二叉搜索树中的插入,删除,修剪 插入这个递归逻辑一开始我自己写的时候没想出来一看题解竟然这么简单。可以记一下或者先试着自己写一下看行不行。DeepSeek最底层遇到 NULL返回新创建的节点指针。中间层非 NULL 的节点执行root-left 递归调用或root-right 递归调用把底层返回的新节点挂到自己身上。然后返回自己root给上一层。最顶层根节点返回整棵树的根节点指针给主调函数lass Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if(rootNULL){ TreeNode*nodenew TreeNode(val); return node; } if(valroot-val)root-leftinsertIntoBST(root-left,val); if(valroot-val)root-rightinsertIntoBST(root-right,val); return root; } };删除DeepSeek这个逻辑很简单但是不要忘了判断keyroot 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(rootNULL)return NULL; else if(root-valkey){ if(!root-left!root-right)return NULL; else if(root-left!root-right)return root-left; else if(!root-leftroot-right)return root-right; else if(root-leftroot-right){ TreeNode* curnullptr; curroot-right; while(cur-left){ curcur-left; } TreeNode* preroot-left; cur-leftpre; TreeNode *tmproot; rootroot-right; delete tmp; return root; }} if(keyroot-val)root-rightdeleteNode(root-right,key); if(keyroot-val)root-leftdeleteNode(root-left,key); return root; } };修改class Solution { public: TreeNode* trimBST(TreeNode* root, int low, int high) { if(rootnullptr)return root; if(root-vallow){ TreeNode*curtrimBST(root-right,low,high); return cur; } if(root-valhigh){ TreeNode*curtrimBST(root-left,low,high); return cur; } root-lefttrimBST(root-left,low,high); root-righttrimBST(root-right,low,high); return root; } };