Maximum Binary Tree

https://leetcode.com/problems/maximum-binary-tree/description/

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

1. The root is the maximum number in the array.
2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
3. 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.

Thoughts

思路和构建BST类似。只是每次分界点是数组所在范围内的最大值。

Code

class Solution {
    private int findMax(int[] nums, int start, int end) {
        int max = nums[start], index = start;
        for (int i = start + 1; i <= end; i++) {
            if (nums[i] > max) {
                max = nums[i];
                index = i;
            }
        }

        return index;
    }

    private TreeNode helper(int[] nums, int start, int end) {
        if (start > end) {
            return null;
        }
        int division = findMax(nums, start, end);
        TreeNode node = new TreeNode(nums[division]);
        node.left = helper(nums, start, division - 1);
        node.right = helper(nums, division + 1, end);
        return node;
    }


    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }
}

Analysis

Errors: 1. 找最大时<=end写成了<end。

最差的情况是排好序的情况,每次要遍历一遍找max. O(n^2).

Ver.2

https://leetcode.com/problems/maximum-binary-tree/discuss/106146/?page=1

如果nums一直递减, 那么不断把节点加到上一个的右子节点. 当出现一个比前面某些节点大的节点nums[i]时, 把最远的那个比它小的nums[j]放到它的左子节点, nums[i]则作为离j最近的左边的比nums[i]的右节点.

/**
 * 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) {
        Deque<TreeNode> stack = new LinkedList<>();
        for (int i = 0; i < nums.length; i++) {
            TreeNode cur = new TreeNode(nums[i]);
            while (!stack.isEmpty() && stack.peek().val < nums[i]) {
                cur.left = stack.pop();
            }
            if (!stack.isEmpty()) {
                stack.peek().right = cur;
            }
            stack.push(cur);
        }

        return stack.isEmpty() ? null : stack.removeLast();
    }
}

Last updated