解
根在中间
左 根 右
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = list()
self.dfs(root, result)
return result
def dfs(self, node, result):
if not node:
return
self.dfs(node.left, result)
result.append(node.val)
self.dfs(node.right, result)
迭代
https://blog.csdn.net/qq_17550379/article/details/80809930
栈
- 只要出栈,必须将其val添加进result
- 所以我们想让左子树的左子树的…最先出栈,因此要不断压入左子树的根节点
- 当当前查看的左子树的根节点为空时,说明它的根无左孩子,中序遍历左中右,无左孩子,那么就将根的val添加进result,并查看这个根的右子树的根节点
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
result = list()
stack = list()
node = root
while stack or node:
# 不断把左边的节点压入栈中
if node:
stack.append(node)
node = node.left
# 对于某一节点 无左节点 则将其val添加进result 并查看其右节点
else:
node = stack.pop()
result.append(node.val)
node = node.right
return result