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;
        }
    };
    
  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/lailailai/p/4832835.html
Copyright © 2011-2022 走看看