Data structure--monotone stack--MaxTree for constructing arrays

Define a binary tree node as follows:

public class Node {
        public int value;
        public Node left;
        public Node right;
        public Node(int data) {
            this.value = data;
        }
    }

  

An array of MaxTree is defined as follows.
The array must have no duplicate elements.
MaxTree is a binary tree, and each value of the array corresponds to a binary tree node.
In each subtree, including the MaxTree tree, the node with the largest value is the head of the tree.
Given an array arr with no repeated elements, write a function that generates a MaxTree of this array, requiring that if the length of the array is N, the time complexity is O(N) and the additional space complexity is O(N).

 

Solution 1: The heap can be used, and the time complexity of constructing the heap is O(N)

Solution 2: Use the monotonic stack to find the closest value to each position in the array that is larger than it, and then let the node whose left and right are both null as the head node, and only the one on the left is the left child of the left node, and only The larger node on the right is the right child of the right node, and the left and right are larger than it, and the smaller of the two is selected as the child of the smaller node

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325337808&siteId=291194637