-
Notifications
You must be signed in to change notification settings - Fork 2
/
q0145.py
42 lines (36 loc) · 1.1 KB
/
q0145.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
#!/usr/bin/python3
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
result = list()
stack = [root]
while len(stack) != 0:
p = stack.pop()
if p:
result.append(p.val)
stack.append(p.left)
stack.append(p.right)
return reversed(result)
def postorderTraversal2(self, root: TreeNode) -> List[int]:
result = list()
if not root:
return result
stack = [root]
pre = root
while len(stack) != 0:
p = stack[-1]
if (p.left == None and p.right == None) or p.left == pre or p.right == pre:
pre = p
stack.pop()
result.append(p.val)
else:
if p.right:
stack.append(p.right)
if p.left:
stack.append(p.left)
return result