-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path94.py
53 lines (38 loc) · 1.2 KB
/
94.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
# leetcode 94 二叉树的中序遍历
## 第一种 递归法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
right = self.inorderTraversal(root.right)
left = self.inorderTraversal(root.left)
return left + [root.val] + right
## 第二种 迭代法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = []
res = []
pointer = root
while stack or pointer:
if pointer:
stack.append(pointer)
pointer = pointer.left
else:
pointer = stack.pop()
res.append(pointer.val)
pointer = pointer.right
return res