【LeetCode】LeetCode 450.删除二叉树中的节点

LeetCode 450.删除二叉树中的节点

题目链接:https://leetcode.cn/problems/delete-node-in-a-bst/

题目

【LeetCode】LeetCode 450.删除二叉树中的节点_第1张图片

【LeetCode】LeetCode 450.删除二叉树中的节点_第2张图片

解答

递归法

class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root == NULL)    return NULL;
        if(root->val == key){
            if(root->left == NULL)  return root->right;
            else if(root->right == NULL)    return root->left;
            else {
                TreeNode* cur = root->right;
                while(cur->left != NULL) {
                    cur = cur->left;
                }
                cur->left = root->left;
                TreeNode* tmp = root;
                root = root->right;
                delete tmp;
                return root;
            }
        }
        if(root->val > key) root->left = deleteNode(root->left, key);
        if(root->val < key) root->right = deleteNode(root->right, key);

        return root;
    }
};

你可能感兴趣的:(#,二叉树专题,leetcode,算法,职场和发展)