1. 程式人生 > 實用技巧 >力扣 - 1382. 將二叉搜尋樹變平衡

力扣 - 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 為樹的節點數