-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtree_operate_python.py
More file actions
86 lines (65 loc) · 1.64 KB
/
tree_operate_python.py
File metadata and controls
86 lines (65 loc) · 1.64 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# Time: 2018/8/21 16:44
# Author: sty
# File: tree_operate_python.py
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ret = []
stack = [root]
while stack:
node = stack.pop()
if node:
ret.append(node.val)
stack.append(node.right)
stack.append(node.left)
return ret
def list_to_treenode(input_values):
if not input_values:
return None
root = TreeNode(int(input_values[0]))
node_queue = [root]
front = 0
index = 1
while index < len(input_values):
node = node_queue[front]
front += 1
item = input_values[index]
index += 1
if item != "null":
left_num = int(item)
node.left = TreeNode(left_num)
node_queue.append(node.left)
if index >= len(input_values):
break
item = input_values[index]
index += 1
if item != "null":
right_num = int(item)
node.right = TreeNode(right_num)
node_queue.append(node.right)
return root
def main():
line = sys.stdin.readline().strip()
values = list(map(str, line.split()))
root = list_to_treenode(values)
pret = Solution().preorderTraversal(root)
print(pret)
if __name__ == '__main__':
main()
"""
input:
3 9 20 null null 15 7
output:
[3, 9, 20, 15, 7]
"""