Solution: recursion
把一个数组看成一棵树(也就是以中点为根,左右为左右子树,依次下去)数组就等价于一个二分查找树。
把中间元素转化为根,然后递归构造左右子树。用二叉树递归的方法来实现,以根作为返回值,每层递归函数取中间元素,作为当前根和赋上结点值,然后左右结点接上左右区间的递归函数返回值。
时间复杂度还是一次树遍历O(n),总的空间复杂度是栈空间O(logn), stack space.
/** * 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 == null || num.length == 0) return null; return sortHelper(num, 0, num.length - 1); } public TreeNode sortHelper(int[] num, int start, int end) { if(start > end) return null; int mid = (start + end) / 2; TreeNode root = new TreeNode(num[mid]); root.left = sortHelper(num, start, mid - 1); root.right = sortHelper(num, mid + 1, end); return root; } }
No comments:
Post a Comment