对题解区的各解法做一个总结:
1、递归
# 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]:
if not root:
return []
return [root.val] + self.inorderTraversal(root.left) + self.inorderTraversal(root.right)
#中序(左根右)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
#后序(左右根)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
return self.inorderTraversal(root.left) + self.inorderTraversal(root.right) + [root.val]
2、迭代
原答主题解链接
借助栈结构使用DFS算法完成
#中序(左根右)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
top = stack.pop()
res.append(top.val)
cur = top.right
return res
#前序(根左右)
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
cur = root
while stack or cur:
while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.left
top = stack.pop()
cur = top.right
return res
#后序(左右根)
#思路:前序的方法改一行,res得出根右左,再倒序输出
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
cur = root
while stack or cur:
while cur:
res.append(cur.val)
stack.append(cur)
cur = cur.right #此时先把右子节点全部压入栈
top = stack.pop()
cur = top.left #这里相应的就是开始搜索最底层的右子节点的左子节点了
return res[::-1] #因为res是按“根右左”存的,所以倒序输出即为左右根
3、标记法
原答主题解链接
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
White, Gray = 0, 1
stack = []
res = []
stack.append((White, root))
while stack:
color, node = stack.pop()
if not node:
continue
if color == White:
stack.append((White, node.right)) #中序(左根右,所以先把右节点压入栈(先进后出))
stack.append((Gray, node)) #如果要求前序(根左右)或后序(左右根)
stack.append((White, node.left)) #根据调换此三行顺序即可
else:
res.append(node.val)
return res
自己编写测试用例时,一般情况和特殊情况都得考虑