LeetCode 1382. 将二叉搜索树变平衡

1382. 将二叉搜索树变平衡

LeetCode 1382. 将二叉搜索树变平衡_第1张图片

【迭代】中序遍历得到顺序,然后递归创建AVL树

class Solution {

    List list = new ArrayList();

    public TreeNode dfs(int left, int right){
        if(left > right) return null;
        if(left == right) return new TreeNode(list.get(left));
        int mid = (left + right) >>> 1;
        TreeNode l = dfs(left, mid - 1);
        TreeNode r = dfs(mid + 1, right);
        return new TreeNode(list.get(mid), l, r);
    }

    public TreeNode balanceBST(TreeNode root) {
        Deque stack = new LinkedList();
        while(!stack.isEmpty() || root != null){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.poll();
            list.add(root.val);
            root = root.right;
        }
        return dfs(0, list.size() - 1);
    }
}

【递归】递归好像要快一些,这次用递归来进行中序遍历

class Solution {

    List list = new ArrayList();

    public void inorder(TreeNode node){
        if(node == null) return;
        inorder(node.left);
        list.add(node.val);
        inorder(node.right);
    }

    public TreeNode dfs(int left, int right){
        if(left > right) return null;
        if(left == right) return new TreeNode(list.get(left));
        int mid = (left + right) >>> 1;
        TreeNode l = dfs(left, mid - 1);
        TreeNode r = dfs(mid + 1, right);
        return new TreeNode(list.get(mid), l, r);
    }

    public TreeNode balanceBST(TreeNode root) {
        inorder(root);
        return dfs(0, list.size() - 1);
    }
}

LeetCode 1382. 将二叉搜索树变平衡_第2张图片

果然要快一些

你可能感兴趣的:(LeetCode,leetcode,AVL树,BST)