Convert Sorted Array to Binary Search Tree (Java)

来源:互联网 发布:淘宝网页版怎么看微淘 编辑:程序博客网 时间:2024/05/13 13:03

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

利用二分法

Source

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode sortedArrayToBST(int[] num) {    if(num.length == 0) return null;        return arrayToBST(num, 0, num.length - 1);   //把arrayToBST的return值作为return值        }    public TreeNode arrayToBST(int[] num, int start, int end){    if(end < start) return null;    int mid = (start + end)/2;        TreeNode root = new TreeNode(num[mid]);    root.left = arrayToBST(num, start, mid - 1);    root.right = arrayToBST(num, mid + 1, end);    return root;    }}


Test

    public static void main(String[] args){    int[] num = {1,2,3,4,5,6,7};        TreeNode root = new Solution().sortedArrayToBST(num);        new Solution().print(root);    }    public void print(TreeNode root){        if(root != null) System.out.println(root.val);    if(root.left != null) print(root.left);    if(root.right != null) print(root.right);        }



0 0
原创粉丝点击