美文网首页
11.Delete Node in a BST

11.Delete Node in a BST

作者: Anaven | 来源:发表于2017-01-02 16:26 被阅读0次

    https://leetcode.com/problems/delete-node-in-a-bst/

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* deleteNode(TreeNode* root, int key) {
            if (!root) {
                return root;
            }
            
            if (key < root->val) {
                root->left = deleteNode(root->left, key);
            } else if (key > root->val) {
                root->right = deleteNode(root->right, key);
            } else {
                if (root->left && root->right) {
                    TreeNode* node = findMin(root->right);
                    root->val = node->val;
                    root->right = deleteNode(root->right, node->val);
                } else {
                    root = root->left ? root->left : root->right;
                }
            }
        
            return root;
        }
        
        TreeNode* findMin(TreeNode* root) {
            if (!root) {
                return root;
            }
            
            while(root->left) {
                root = root->left;    
            }
            
            return root;
        }
    };
    

    相关文章

      网友评论

          本文标题:11.Delete Node in a BST

          本文链接:https://www.haomeiwen.com/subject/qvbwvttx.html