# Max Tree

#### Max Tree

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

• The root is the maximum number in the array
• The left subtree and right subtree are the max trees of the subarray divided by the root number.

Construct the max tree by the given array.

Example

Given `[2, 5, 6, 0, 3, 1]`, the max tree constructed by this array is:

```<code>    6
/ \
5   3
/   / \
2   0   1
</code>```
Challenge

O(n) time and memory.

Solution: 用stack来维护在每个数出现前比它大得数。

When new node comes in, if it is larger than the peek, stack.pop() and at the same time append it as the new node’s left child. until the stack peek is larger than the new node or the stack is empty, at this time, the peek.right = new node. then we push new node into the stack. if the stack is empty when the new node is pushed, the new node is the temporary root.

```public TreeNode maxTree(int[] A) {
if (A == null || A.length == 0) {
return null;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode root = null;
for (int i = 0; i < A.length; i++) {
TreeNode curr = new TreeNode(A[i]);
while (!stack.isEmpty() && A[i] >= stack.peek().val) {
TreeNode tmp = stack.pop();
tmp.right = curr.left;
curr.left = tmp;
}
if (!stack.isEmpty()) {
stack.peek().right = curr;
} else {
root = curr;
}
stack.push(curr);
}
return root;
}```
{"ft_lang_label":"__label__en","ft_lang_prob":0.67638195,"math_prob":0.9897186,"size":1323,"snap":"2022-40-2023-06","text_gpt3_token_len":396,"char_repetition_ratio":0.14708112,"word_repetition_ratio":0.0,"special_character_ratio":0.31519273,"punctuation_ratio":0.19127516,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.998219,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-09-28T19:20:56Z\",\"WARC-Record-ID\":\"<urn:uuid:4f8b9b5a-76a1-49df-8c4d-308559d6111d>\",\"Content-Length\":\"31643\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:10db6740-cd13-4432-82cc-63421887caf6>\",\"WARC-Concurrent-To\":\"<urn:uuid:53d84e88-203f-4858-bc12-eae6101ad7b4>\",\"WARC-IP-Address\":\"166.62.77.128\",\"WARC-Target-URI\":\"http://ying.ninja/?p=727\",\"WARC-Payload-Digest\":\"sha1:RPDGWYW7BFLCFMO27R4YJPVBWE5NZFUN\",\"WARC-Block-Digest\":\"sha1:RLJFLDIOBWFE2Z5DGIY255W3BTNXBLGN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030335276.85_warc_CC-MAIN-20220928180732-20220928210732-00393.warc.gz\"}"}