image.png

解决思路

image.png

  1. class Solution {
  2. int[] nums;
  3. public TreeNode helper(int left, int right) {
  4. if (left > right) return null;
  5. // always choose left middle node as a root
  6. int p = (left + right) / 2;
  7. // inorder traversal: left -> node -> right
  8. TreeNode root = new TreeNode(nums[p]);
  9. root.left = helper(left, p - 1);
  10. root.right = helper(p + 1, right);
  11. return root;
  12. }
  13. public TreeNode sortedArrayToBST(int[] nums) {
  14. this.nums = nums;
  15. return helper(0, nums.length - 1);
  16. }
  17. }