-
Notifications
You must be signed in to change notification settings - Fork 90
/
Max Tree.py
64 lines (46 loc) · 1.45 KB
/
Max Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
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 is
6
/ \
5 3
/ / \
2 0 1
Challenge
O(n) time complexity
"""
__author__ = 'Danyang'
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution(object):
def maxTree(self, A):
"""
Cartesian Tree, Heap-ordered, treap, stack O(n)
http://en.wikipedia.org/wiki/Cartesian_tree
using stack
1. construct left tree and maintain the Cartesian tree
2. connect right tree
O(n) since each node on the tree is pushed and popped out from stack once
:param A: Given an integer array with no duplicates.
:return: The root of max tree.
"""
stk = []
for a in A:
cur = TreeNode(a)
while stk and stk[-1].val <= cur.val:
pre = stk.pop()
pre.right = cur.left
cur.left = pre
stk.append(cur)
pre = None
while stk:
cur = stk.pop()
cur.right = pre
pre = cur
return pre