Convert Sorted Array to Binary Search Tree

来源:互联网 发布:淘宝企业账号怎么注册 编辑:程序博客网 时间:2024/06/13 01:14
/** * 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) {        return arrToBST(num, 0, num.length-1);    }    public TreeNode arrToBST(int[] num, int l, int r){        if (l>r) return null;        TreeNode root = new TreeNode(num[(l+r)/2]);        root.left  = arrToBST(num, l, (l+r)/2-1);        root.right = arrToBST(num, (l+r)/2+1, r);        return root;    }}

0 0
原创粉丝点击