栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode

思路

二叉搜索树的中序遍历就是一个有序的序列

  1. 先将二叉搜索树中序遍历得到有序的序列存入数组中
	// 中序遍历二叉树
    public void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        list.add(root.val);
        inorder(root.right);
    }
  1. 在数组中删除对应的元素list.remove((Integer) key)
  2. 根据删除后的数组构建一颗二叉搜索树
	// 根据有序数组构建二叉搜索树
    public TreeNode buildTree(int start, int end) {
        if (start > end) return null;
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(list.get(mid));
        root.left = buildTree(start, mid - 1);
        root.right = buildTree(mid + 1, end);
        return root;
    }
代码实现(java)
class Solution {
    List list = new ArrayList<>();
    public TreeNode deleteNode(TreeNode root, int key) {
        // 先遍历得到序列
        inorder(root);
        // 删除对应元素
        list.remove((Integer) key);
        // 重新构成一颗二叉搜索树
        return buildTree(0, list.size() - 1);
    }

    // 根据有序数组构建二叉搜索树
    public TreeNode buildTree(int start, int end) {
        if (start > end) return null;
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(list.get(mid));
        root.left = buildTree(start, mid - 1);
        root.right = buildTree(mid + 1, end);
        return root;
    }

    // 中序遍历二叉树
    public void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        list.add(root.val);
        inorder(root.right);
    }
}
补充(有序链表转换为二叉搜索树#109)
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        return buildTree(head);
    }

    public TreeNode buildTree(ListNode head) {
        if (head == null) return null;
        else if (head.next == null) return new TreeNode(head.val);

        // 根基快慢指针找到链表中点
        ListNode slow = head; // 存储链表中点
        ListNode fast = head;
        ListNode pre = null; // 存储链表中点的前一个节点, 用来移除中点
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        pre.next = null;  // 去除中点

        TreeNode root = new TreeNode(slow.val);
        root.left = buildTree(head);
        root.right = buildTree(slow.next);

        return root;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/343581.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号