Loading

力扣 - 1382. 将二叉搜索树变平衡

题目

1382. 将二叉搜索树变平衡

思路

  • 由于BST二叉搜索树的中序遍历是升序的,所以我们可以先通过中序遍历将该树转换为链表
  • 然后再通过中序遍历,此时选取的是链表的中点作为树的根节点,将链表恢复为一颗平衡的二叉搜索树

代码

class Solution {
    class ListNode{
        int val;
        ListNode next;
        public ListNode() {
        }
        public ListNode(int x) {
            val = x;
        }
    }
    
    public ListNode dummy = new ListNode();
    public ListNode point = dummy;
    
    public TreeNode balanceBST(TreeNode root) {
        inOrderTraversal(root);
        return traversal(dummy.next);
    }

    public void inOrderTraversal(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrderTraversal(root.left);
        point.next = new ListNode(root.val);
        point = point.next;
        inOrderTraversal(root.right);
    }

    public TreeNode traversal(ListNode head) {
        if (head == null) {
            return null;
        }
        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;
        }

        TreeNode root = new TreeNode(slow.val);
        pre.next = null;
        root.left = traversal(head);
        root.right = traversal(slow.next);
        return root;
    }
}

复杂度分析

  • 时间复杂度:\(O(N)\),其中 N 为树的节点数
  • 空间复杂度:\(O(N)\),其中 N 为树的节点数
posted @ 2020-11-22 20:07  linzeliang  阅读(83)  评论(0)    收藏  举报