zoukankan      html  css  js  c++  java
  • LintCode Remove Node in Binary Search Tree

    Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.

    以后估计不会再写了

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param root: The root of the binary search tree.
         * @param value: Remove the node with given value.
         * @return: The root of the binary search tree after removal.
         */
        TreeNode* removeNode(TreeNode* root, int value) {
            // write your code here
            if (root == NULL) {
                return NULL;
            }
    
            if (root->val > value) {
                root->left = removeNode(root->left, value);
                return root;
            } else if (root->val < value) {
                root->right= removeNode(root->right, value);
                return root;
            }
            if (root->left == NULL && root->right == NULL) {
                delete root;
                return NULL;
            }
            if (root->left == NULL || root->right == NULL) {
                TreeNode* child = root->left ? root->left : root->right;
                root->left = child->left;
                root->right = child->right;
                root->val = child->val;
                delete child;
                return root;
            }
            TreeNode* min2move = findMin(root->right);
            root->val = min2move->val;
            root->right = removeNode(root->right, min2move->val);
            return root;
        }
        
        TreeNode* findMin(TreeNode* root) {
            TreeNode* curr = root;
            TreeNode* prev = NULL;
            while (curr != NULL) {
                prev = curr;
                curr = curr->left;
            }
            return prev;
        }
    };
    
  • 相关阅读:
    关于登录或授权页面的错误提示
    弱网环境模拟工具
    Android Fragment 深度解析
    排序算法(七)
    排序算法(六)
    排序算法(五)
    java之数组
    排序算法(四)
    排序算法(三)
    排序算法(二)
  • 原文地址:https://www.cnblogs.com/lailailai/p/4832835.html
Copyright © 2011-2022 走看看