-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMax binary tree.py
More file actions
35 lines (27 loc) · 829 Bytes
/
Copy pathMax binary tree.py
File metadata and controls
35 lines (27 loc) · 829 Bytes
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
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def constructMaximumBinaryTree(nums):
if not nums:
return None
max_val = max(nums)
max_index = nums.index(max_val)
root = TreeNode(max_val)
root.left = constructMaximumBinaryTree(nums[:max_index])
root.right = constructMaximumBinaryTree(nums[max_index+1:])
return root
def preorderTraversal(root):
if root:
print(root.val,end=" ")
if not root.left and not root.right:
return
preorderTraversal(root.left)
preorderTraversal(root.right)
else:
print("null",end=" ")
if __name__ == "__main__":
nums = list(map(int,input().split(" ")))
root = constructMaximumBinaryTree(nums)
preorderTraversal(root)