654. Maximum Binary Tree
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.
Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:
6
/ \
3 5
\ /
2 0
\
1
- The size of the given array will be in the range [1,1000].
- mine
Runtime 23 ms
//O(n^2)time O(n)space
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
Map<Integer,Integer> indexs = new HashMap<>();
for(int i = 0; i < nums.length; i++){
indexs.put(nums[i],i);
}
Arrays.sort(nums);
TreeNode root = new TreeNode(nums[nums.length - 1]);
if(nums.length == 1){
return root;
}
for(int i = nums.length - 2; i >= 0; i--){
getNode(root,indexs,nums[i]);
}
return root;
}
public void getNode(TreeNode node, Map<Integer,Integer> indexs, int value){
if(indexs.get(value) > indexs.get(node.val)){
if(node.right != null){
getNode(node.right, indexs, value);
}else{
node.right = new TreeNode(value);
}
}else{
if(node.left != null){
getNode(node.left, indexs, value);
}else{
node.left = new TreeNode(value);
}
}
}
}
- the most votes
Runtime 12 ms
// O(n)time O(n)space
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
Deque<TreeNode> stack = new LinkedList<>();
for(int i = 0; i < nums.length; i++) {
TreeNode curr = new TreeNode(nums[i]);
while(!stack.isEmpty() && stack.peek().val < nums[i]) {
curr.left = stack.pop();
}
if(!stack.isEmpty()) {
stack.peek().right = curr;
}
stack.push(curr);
}
return stack.isEmpty() ? null : stack.removeLast();
}
}
- the faster
Runtime 5 ms
// O(nlogn)time O(1)space
public class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null) return null;
return build(nums, 0, nums.length - 1);
}
private TreeNode build(int[] nums, int start, int end) {
if (start > end) return null;
int idxMax = start;
for (int i = start + 1; i <= end; i++) {
if (nums[i] > nums[idxMax]) {
idxMax = i;
}
}
TreeNode root = new TreeNode(nums[idxMax]);
root.left = build(nums, start, idxMax - 1);
root.right = build(nums, idxMax + 1, end);
return root;
}
}