微软面试题: LeetCode 450 . 删除二叉搜索树中的节点 middle 出现次数:3

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* deleteNode(TreeNode* root, int key)
15     {
16         if(root == nullptr)
17         {
18             return nullptr;
19         }
20         if(key < root->val)//目标节点在左子树中,递归处理左子树,返回结果赋予root 左指针
21         {
22             root->left = deleteNode(root->left,key);
23             return root;
24         }
25         else if(key > root->val)//目标节点在右子树中,递归处理右子树,返回结果赋予root 右指针
26         {
27             root->right = deleteNode(root->right, key);
28             return root;
29         }
30         else //root   就是需要删除的目标节点
31         {
32             if(root->left == nullptr && root->right == nullptr) //root 是叶节点,删除root ,返回nullptr
33             {
34                 delete root;
35                 root = nullptr;
36                 return root;
37             }
38             else if(root->left != nullptr && root->right == nullptr)//root只有左子树,删除root,返回左子树
39             {
40                 TreeNode* leftNode = root->left;
41                 delete root;
42                 root = nullptr;
43                 return leftNode;
44             }
45             else if(root->left == nullptr && root->right != nullptr)//root只有右子树,删除root,返回右子树
46             {
47                 TreeNode* rightNode = root->right;
48                 delete root;
49                 root = nullptr;
50                 return rightNode;
51             }
52             else //既有左子树又有右子树,将右子树上的最小值,覆盖掉root上的值,并删除掉右子树上的最小值节点,并将其再接到root->right上
53             {
54                 TreeNode* pre = root->right;
55                 while(pre->left)
56                 {
57                     pre = pre->left;
58                 }
59                 root->val = pre->val;
60                 //将任务 “删除掉右子树上的最小值节点” 交给递归,并将递归得到的结果,再接到root->right上
61                 root->right = deleteNode(root->right, pre->val);
62                 return root;
63             }
64         }
65         return root;
66     }
67 };

 

posted @ 2020-11-27 00:22  谁在写西加加  阅读(99)  评论(0编辑  收藏  举报