zoukankan      html  css  js  c++  java
  • 450 Delete Node in a BST 删除二叉搜索树中的结点

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

    C++:

    /**
     * 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 nullptr;
            }
            if (root->val > key)
            {
                root->left = deleteNode(root->left, key);
            } 
            else if (root->val < key) 
            {
                root->right = deleteNode(root->right, key);
            } 
            else 
            {
                if (!root->left || !root->right) 
                {
                    root = (root->left) ? root->left : root->right;
                } 
                else 
                {
                    TreeNode *cur = root->right;
                    while (cur->left)
                    {
                        cur = cur->left;
                    }
                    root->val = cur->val;
                    root->right = deleteNode(root->right, cur->val);
                }
            }
            return root;
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/6228252.html

  • 相关阅读:
    java内存泄露
    hbase java api
    配置CRT远程登录
    kafka分区消费模型
    JAVA内存区域
    JVM分代和垃圾回收
    spring中bean的作用域
    分布式RPC
    session共享
    ZooKeeper实现分布式session
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8900960.html
Copyright © 2011-2022 走看看