递归实现
二叉树中序遍历按照 左 中 右 的顺序进行。递归实现的原理 先向下遍历左子树,当左子树为空时,记录当前节点,在遍历右子树。
终止条件:当前节点为空时
函数内:递归的调用左节点,打印当前节点,再递归调用右节点
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.result = []
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
def midTraversal(root):
if not root:
return
left = midTraversal(root.left)
self.result.append(root.val)
right = midTraversal(root.right)
midTraversal(root)
return self.result
迭代实现
# 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 []
res, stack = list(), list()
curr = root
while curr or len(stack):
while curr:
stack.append(curr)
curr = curr.left
node = stack.pop()
res.append(node.val)
curr = node.right
return res