Problem
Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height.
Example
Given [1,2,3,4,5,6,7]
, return
4
/ \
2 6
/ \ / \
1 3 5 7
Note
二分法找到数组的中位数,置为树的root,递归找到前半段和后半段的中位数,分别置为左右子树。直到start = mid或end = mid为止。
Solution
Recursive
public class Solution {
public TreeNode sortedArrayToBST(int[] A) {
return helper(0, A.length - 1, A);
}
public TreeNode helper(int start, int end, int[]A) {
if (start > end) return null;
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(A[mid]);
root.left = helper(start, mid - 1, A);
root.right = helper(mid + 1, end, A);
return root;
}
}
Iterative
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) return null;
TreeNode head = new TreeNode(0);
Deque<TreeNode> nodeStack = new LinkedList<>();
Deque<Integer> leftIndexStack = new LinkedList<>();
Deque<Integer> rightIndexStack = new LinkedList<>();
nodeStack.push(head);
leftIndexStack.push(0);
rightIndexStack.push(nums.length-1);
while (!nodeStack.isEmpty()) {
TreeNode curNode = nodeStack.pop();
int left = leftIndexStack.pop();
int right = rightIndexStack.pop();
int mid = left+(right-left)/2;
curNode.val = nums[mid];
if (left < mid) {
curNode.left = new TreeNode(0);
nodeStack.push(curNode.left);
leftIndexStack.push(left);
rightIndexStack.push(mid-1);
}
if (mid < right) {
curNode.right = new TreeNode(0);
nodeStack.push(curNode.right);
leftIndexStack.push(mid+1);
rightIndexStack.push(right);
}
}
return head;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。