-
Notifications
You must be signed in to change notification settings - Fork 0
/
Traversalnew.py
68 lines (57 loc) · 1.79 KB
/
Traversalnew.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
65
66
67
68
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : Traversalnew.py
@Time : 2024/10/09 09:39:50
@Author : Zihao Zheng
@Email : [email protected]
'''
from typing import List
class TreeNode():
def __init__(self,val=0,left=None,right=None):
self.value=val
self.left=left
self.right=right
return
class Solution:
def preorder(self,root:TreeNode):
if not root:
return []
stack=[root]
result=[]
while stack:
node=stack.pop() #弹一个 放入两个(右左)子节点
result.append(node.value)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
def innerorder(self,root:TreeNode):
if not root:
return []
stack=[]
result=[]
cur=root #引用一个指针
while cur or stack:
if cur: #访问到最下面的左子树
stack.append(cur)
cur=cur.left
else:
cur=stack.pop() #弹出一个 指针右移
result.append(cur.value)
cur=cur.right
return result
def posterorder(self,root:TreeNode):
if not root:
return []
stack=[root]
result=[]
while stack:
node=stack.pop() #弹一个 放入两个(右左)子节点
result.append(node.value)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result[::-1]