0%

Leetcode 94 二叉树的中序遍历

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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]:
ans, stack = [], []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
ans.append(root.val)
root = root.right
return ans