Guest User

Untitled

a guest
Jul 16th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. //Recursive solution: avoid copy array
  2. //Time: O(n), 7ms
  3. //Space: O(h)
  4. class Solution {
  5. public TreeNode constructMaximumBinaryTree(int[] nums) {
  6. return constructR(nums, 0, nums.length);
  7. }
  8.  
  9. private TreeNode constructR(int[] nums, int begin, int end) {
  10. if(begin >= end) return null;
  11. int max = begin;
  12. for(int i = begin; i < end; i++) {
  13. if(nums[i] > nums[max]) {
  14. max = i;
  15. }
  16. }
  17. TreeNode root = new TreeNode(nums[max]);
  18. root.left = constructR(nums, begin, max);
  19. root.right = constructR(nums, max + 1, end);
  20. return root;
  21. }
  22. }
  23. /**
  24. * Definition for a binary tree node.
  25. * public class TreeNode {
  26. * int val;
  27. * TreeNode left;
  28. * TreeNode right;
  29. * TreeNode(int x) { val = x; }
  30. * }
  31. */
Add Comment
Please, Sign In to add comment