Skip to content

Commit ef6a23e

Browse files
authored
Create Binary Tree Preorder Traversal.py
1 parent 7f1afb7 commit ef6a23e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Binary Tree Preorder Traversal.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
Given a binary tree, return the preorder traversal of its nodes' values.
3+
4+
Example:
5+
6+
Input: [1,null,2,3]
7+
1
8+
\
9+
2
10+
/
11+
3
12+
13+
Output: [1,2,3]
14+
'''
15+
16+
# Definition for a binary tree node.
17+
# class TreeNode(object):
18+
# def __init__(self, x):
19+
# self.val = x
20+
# self.left = None
21+
# self.right = None
22+
23+
class Solution(object):
24+
def preorderTraversal(self, root):
25+
"""
26+
:type root: TreeNode
27+
:rtype: List[int]
28+
"""
29+
if not root:
30+
return []
31+
32+
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)

0 commit comments

Comments
 (0)