1. 程式人生 > >升序陣列轉成二叉排序樹

升序陣列轉成二叉排序樹

題目

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

分析

將二叉查詢樹進行中序遍歷,就可以得到一個升序排序的陣列,因此,一個已經排序的陣列可以看做一箇中序遍歷得到的陣列,要得到一個高度平衡的二叉查詢樹,可以使得左右子樹的節點數儘可能相等。因此,可以採用二分法將陣列分為兩個子陣列,中間值作為父節點,左邊的子陣列作為左子樹,右邊的子陣列作為右子樹進行遞迴,這樣就可以得到一個高度平衡的二叉查詢樹。

程式碼

public class TreeNode {
    int value;

    TreeNode left;

    TreeNode right;

    TreeNode(int value) {
        this.value = value;
    }

    public static TreeNode sortedArrayToBST(int[] num) {

        return helper(0, num.length - 1, num);

    }

    private static TreeNode helper(int i, int j, int[] num) {
        if (i > j)
            return null;
        else if (i == j) {
            return new TreeNode(num[i]);
        } else {
            int mid = (i + j + 1) / 2;
            TreeNode node = new TreeNode(num[mid]);
            node.left = helper(i, mid - 1, num);
            node.right = helper(mid + 1, j, num);
            return node;
        }
    }
    
    @Override
    public String toString() {
        return printTree(this,0);
    }
    
    private String printTree(TreeNode node,int depth) {
        StringBuilder result = new StringBuilder();
        result.append(printSpace(depth));
        result.append(node.value);
        result.append("\n");
        TreeNode left = node.left;
        if(left!=null) {
            result.append(printTree(left, depth+1));
        }
        TreeNode right = node.right;
        if(right!=null) {
            result.append(printTree(right, depth+1));
        }
        
        return result.toString();
    }
    
    private String printSpace(int depth) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            result.append("\t");
        }
        return result.toString();
    }
    
    public static void main(String[] args) {
        int arr[]= { 1, 2, 4, 3, 6, 8 };
        Arrays.sort(arr);
        TreeNode tree = sortedArrayToBST(arr);
        System.out.println(tree);
    }
}
轉載自http://blog.csdn.net/zh_ang_lei/article/details/72814814