Rebalancing an arbitrary BST?

后端 未结 4 814
抹茶落季
抹茶落季 2020-12-04 09:43

Reference: I was asked this question @MS SDE interview, 3rd round. And it\'s not a homework problem. I also gave it a thought and mentioning my approach bel

4条回答
  •  清歌不尽
    2020-12-04 09:45

    This will convert your normal BST into a balanced BST with minimum possible height in O(n). First, save all your nodes sorted into a vector. Then, the root is the mid element and recursively build a tree from 0 to mid-1 as its left and build a tree from mid+1 to vector.size()-1 as its right child. After all these steps root keeps the balanced BST with the min-height.

        import java.util.Vector;
    
            public class ConvertBSTIntoBalanced {
    
                public static void main(String[] args) {
                    TreeNode node1 = new TreeNode(1);
                    TreeNode node2 = new TreeNode(2);
                    TreeNode node3 = new TreeNode(3);
                    TreeNode node4 = new TreeNode(4);
                    node1.right = node2;
                    node2.right = node3;
                    node3.right = node4;
                    ConvertBSTIntoBalanced convertBSTIntoBalanced = new ConvertBSTIntoBalanced();
                    TreeNode balancedBSTRoot = convertBSTIntoBalanced.balanceBST(node1);
                }
    
                private void saveNodes(TreeNode node, Vector nodes) {
                    if (node == null)
                        return;
                    saveNodes(node.left, nodes);
                    nodes.add(node);
                    saveNodes(node.right, nodes);
                }
    
                private TreeNode buildTree(Vector nodes, int start, int end) {
                    if (start > end)
                        return null;
                    int mid = (start + end) / 2;
                    TreeNode midNode = nodes.get(mid);
                    midNode.left = buildTree(nodes, start, mid - 1);
                    midNode.right = buildTree(nodes, mid + 1, end);
                    return midNode;
                }
    
                public TreeNode balanceBST(TreeNode root) {
                    Vector nodes = new Vector<>();
                    saveNodes(root, nodes);
                    return buildTree(nodes, 0, nodes.size() - 1);
                }
    
            public class TreeNode {
    
            public Integer val;
            public TreeNode left;
            public TreeNode right;
    
            public TreeNode(Integer x) {
                val = x;
            }
    
        }
    
            }
    

    I hope it helps.

提交回复
热议问题