zoukankan      html  css  js  c++  java
  • 二叉搜索树的操作

    2018-07-31 15:46:34

    一、插入 Insert into a Binary Search Tree

    问题描述:

    问题求解:

        public TreeNode insertIntoBST(TreeNode root, int val) {
            if (root == null) {
                TreeNode node = new TreeNode(val);
                return node;
            }
            if (root.val > val) root.left = insertIntoBST(root.left, val);
            else root.right = insertIntoBST(root.right, val);
            return root;
        }
    

    二、删除 Delete Node in a BST

    问题描述:

    问题求解:

        public TreeNode deleteNode(TreeNode root, int key) {
            if (root == null) return null;
            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 == null) return root.right;
                if (root.right == null) return root.left;
                TreeNode minNode = root.right;
                while (minNode.left != null) minNode = minNode.left;
                root.val = minNode.val;
                root.right = deleteNode(root.right, root.val);
            }
            return root;
        }
    
  • 相关阅读:
    环形二维数组
    梦断代码(三)
    梦断代码(二)
    梦断代码(一)
    CNblogs用户体验
    《软件工程》--读书笔记三
    《软件工程》--读书笔记二
    《软件工程》--读书笔记一
    找出水王
    典型用户
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/9396317.html
Copyright © 2011-2022 走看看