• 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;
        }
    };
    
  • 相关阅读:
    CSS布局简史
    行块布局(如何理解Display:None,Block,Inline,Inline-Block)
    JQuery的基础学习
    在网页中添加一个可以收藏的功能
    PHPcms需要用到
    TP框架里面当访问不存在的操作方法时让其不显示错误页面(空控制器空操作)
    验证码上传文件
    关于API
    webapp的学习
    在ThinkPHP里面进行表单验证
  • 原文地址:https://www.cnblogs.com/lailailai/p/4832835.html
Copyright © 2020-2023  润新知