-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Challenge.py
More file actions
51 lines (38 loc) · 1.08 KB
/
Copy pathBinary_Tree_Challenge.py
File metadata and controls
51 lines (38 loc) · 1.08 KB
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
# Definition for a binary tree node.
#This class is a constructor
#When you create an object 'node' it sets attributes 'val=0', 'left=None', 'right=None'
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
#Recursively traverses a binary tree in pre-order when given the root node
class Solution(object):
def preorderTraversal(self, root):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
output = []
if root:
output.append(root.val)
output = output + self.preorderTraversal(root.left)
output = output + self.preorderTraversal(root.right)
return output
root = TreeNode()
a1 = TreeNode()
a2 = TreeNode()
a3 = TreeNode()
a4 = TreeNode()
root.val = 0
a1.val = 5
a2.val = 2
a3.val = 7
a4.val = 9
root.left = a1
root.right = a2
a1.left = a3
a2.right = a4
trvrse = Solution()
print(trvrse.preorderTraversal(root))