Maximum Binary Tree
Question
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Solution
第一個解法自己有寫出來,用 recursion,只不過會需要 O(N2)。是自頂向下的方向來建構樹
public TreeNode constructMaximumBinaryTree(int[] nums) {
TreeNode head = helper(nums, 0, nums.length - 1);
return head;
}
public TreeNode helper(int[] nums, int start, int end) {
if (start < 0 || end >= nums.length || end < start) {
return null;
}
int max = Integer.MIN_VALUE;
int maxIndex = 0;
for (int i = start; i <= end; i++) {
if (nums[i] > max) {
max = nums[i];
maxIndex = i;
}
}
TreeNode head = new TreeNode(max);
head.left = helper(nums, start, maxIndex - 1);
head.right = helper(nums, maxIndex + 1, end);
return head;
}
最佳解會是 O(N),用遞增 stack。變成自底向上的建構樹
Stack<TreeNode> stack = new Stack<TreeNode>();
for (int i = 0; i <= nums.length; i++) {
TreeNode node = i == nums.length? new TreeNode(Integer.MAX_VALUE) : new TreeNode(nums[i]);
if (!stack.isEmpty() && stack.peek().val < node.val) {
TreeNode curt = stack.pop();
TreeNode root = curt;
while (!stack.isEmpty() && stack.peek().val < node.val) {
root = stack.pop();
root.right = curt;
curt = root;
}
node.left = root;
}
stack.push(node);
}
return stack.peek().left;